Tuesday, September 4, 2012

PHP multidimensional arrays with recursive function


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 = true) {
    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';

No comments:

Post a Comment