-1

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".

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

0

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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Your task is asking how to create an indexed array of arrays where qualifying rows must contain a specified value at a specified key.

function filter($array, $value, $key) {
    return array_values(
               array_filter(
                   $array,
                   fn($row) => array_key_exists($key, $row) && $row[$key] === $value
               )
           );
}

The array_filter() call returns true (keeps the row) if the key exists and the value at that key is an exact match.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136