Search code examples
phparraysmultidimensional-array

How to check if a value is in a multidimensional array


I use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a)) 
{
    echo "Got Irix";
}

//print_r($a);

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

or I shouldn't be using in_array() when comes to the multidimensional array?


Solution

  • in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

    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:

    $b = array(array("Mac", "NT"), array("Irix", "Linux"));
    echo in_array_r("Irix", $b) ? 'found' : 'not found';