How to Filter Multidimensional Array by Key Value in PHP

PHP array_filter() function filters elements of an array by a callback function and it can be used for many purposes. The array_filter() function provides a short and simple way to filter multidimensional array by key and value.

In the following example code, we will show you how to filter values from multidimensional array similar to SQL LIKE using the array_filter() function in PHP. Using this code, you can filter multidimensional arrays by specific key and value.

$array = array(
    array(
'name' => 'John Doe''email' => 'john@gmail.com'),
    array(
'name' => 'Marry Lies''email' => 'marry@gmail.com'),
    array(
'name' => 'Andrew Joe''email' => 'andrew@gmail.com'),
);

$like 'jo';

$result array_filter($array, function ($item) use ($like) {
    if (
stripos($item['name'], $like) !== false) {
        return 
true;
    }
    return 
false;
});

The above code returns the filtered array.

Array
(
    [0] => Array
        (
            [name] => John Doe
            [email] => john@gmail.com
        )

    [2] => Array
        (
            [name] => Andrew Joe
            [email] => andrew@gmail.com
        )

)

6 Comments

  1. LEonardo Said...
  2. Lou Said...
  3. Anant Singh Said...
  4. Gerald Omaghomi Said...
  5. Balaji Said...
  6. Kash Said...

Leave a reply

keyboard_double_arrow_up