php array_filter get keys using pass variable example

Simple example for php array_filter get keys with array_filter pass variable in process.

Use array_filter for search in multidimensional array, in which have child array with root level key. Below is example of array.

$arr = [
    'key1' => ['item1', 'item2'],
    'key2' => ['item3', 'item4'],
    'key3' => ['item5', 'item6'],
];

Now what is requirement?

Suppose you have string that you want to search in inner child array and want key of that child array.

Let’s start step by step process which include use of php array_filter, array_filter pass variable and php array_filter get keys.

php array_filter pass variable

Just by adding use($variable) after function. $variable will available in filter process.

$myKey = array_filter( $arr, function($item) use($variable){
   echo $variable;
});

php array_filter get keys

$arr = [
    'key1' => ['item1', 'item2'],
    'key2' => ['item3', 'item4'],
    'key3' => ['item5', 'item6'],
];

$variable = 'item3';

$myKey = array_filter( $arr, function($item, $key) use($variable){
   return in_array($variable, $item) ? $key : null;
}, ARRAY_FILTER_USE_BOTH);

$myKey
//Array ( [key2] => Array ( [0] => item3 [1] => item4 ) )

key($myKey);
//key2