Tuesday, November 29, 2016

in_array() and multidimensional array

in_array  is not work on multidimensional arrays. You should be 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;
}


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

No comments:

Post a Comment