in_array() and multidimensional array

前端 未结 22 1320
眼角桃花
眼角桃花 2020-11-22 00:30

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\"         


        
22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 01:21

    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';
    

提交回复
热议问题