Search for a Value in a Multidimensional Array in PHP
A recursive function to check whether a value exists inside a multidimensional PHP array.
I needed to check whether a value existed inside a multidimensional PHP array, and the native functions didn’t cover the case — especially when array keys are strings.
The solution
A recursive function that traverses the entire nested structure:
function in_multiarray($elem, $array)
{
while (current($array) !== false) {
if (current($array) == $elem) {
return true;
} elseif (is_array(current($array))) {
if (in_multiarray($elem, current($array))) {
return true;
}
}
next($array);
}
return false;
}
How to use it
$array = [
'level1' => [
'level2' => [
'target_value',
'other_value'
]
]
];
$found = in_multiarray('target_value', $array); // true
The function descends recursively through each level of the array. If the current element is another array, it calls itself to continue the search.
Hope it helps!