in_array() and multidimensional array

前端 未结 22 1322
眼角桃花
眼角桃花 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:16

    The accepted solution (at the time of writing) by jwueller

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

    Is perfectly correct but may have unintended behaviuor when doing weak comparison (the parameter $strict = false).

    Due to PHP's type juggling when comparing values of different type both

    "example" == 0
    

    and

    0 == "example"
    

    Evaluates true because "example" is casted to int and turned into 0.

    (See Why does PHP consider 0 to be equal to a string?)

    If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison:

    function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $item) {
    
            if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
                $item = (string)$item;
            }
    
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return true;
            }
        }
    
        return false;
    }
    

提交回复
热议问题