Searching Multidimensional Arrays with in_array()
While the in_array() function is a convenient tool for checking the existence of a value within an array, it falls short when dealing with arrays that possess a multidimensional structure. To overcome this limitation, consider the following:
Custom Recursive Function
Instead of relying on in_array(), you can employ a recursive function like in_array_r:
function in_array_r($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; }
Usage:
To utilize the in_array_r function, provide it with the needle (value you seek), the haystack (multidimensional array), and an optional strict parameter (controls strict equality comparison). For example:
$b = array(array("Mac", "NT"), array("Irix", "Linux")); echo in_array_r("Irix", $b) ? 'found' : 'not found';
The above is the detailed content of How Can I Efficiently Search Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!