phparraysfilterexact-match

Only retain array rows which contain a specified value at a specified key


I have this function:

function filter($array, $like, $kol) {
    $filtered = array_filter($array, function ($item) use ($kol, $like) {
        return stripos($item[$kol], $like) !== false;
    });
    
    return array_values($filtered);
}

How can I modify this to only return exact values as $like? Now it searches for "like $like".


Solution

  • Using stripos will:

    Find the numeric position of the first occurrence of needle in the haystack string.

    If you want to check if the value of $item[$kol] is equal to $like you can compare the strings

    return $item[$kol] === $like
    

    As you are indexing into the array, you could first check if the key exists.

    For example

    function filter($array, $like, $kol) {
        $filtered = array_filter($array, function ($item) use ($kol, $like) {
            if (array_key_exists($kol, $item)) {
                return $item[$kol] === $like;
            }
            return false;
        });
    
        return array_values($filtered);
    }
    

    Php demo