in_array() and multidimensional array

前端 未结 22 1962
眼角桃花
眼角桃花 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 01:13

    Since PHP 5.6 there is a better and cleaner solution for the original answer :

    With a multidimensional array like this :

    $a = array(array("Mac", "NT"), array("Irix", "Linux"))
    

    We can use the splat operator :

    return in_array("Irix", array_merge(...$a), true)
    

    If you have string keys like this :

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

    You will have to use array_values in order to avoid the error Cannot unpack array with string keys :

    return in_array("Irix", array_merge(...array_values($a)), true)
    

提交回复
热议问题