PHP's variable type leniency

后端 未结 3 1114
耶瑟儿~
耶瑟儿~ 2020-12-18 07:26

The most recent comment on PHP\'s in_array() help page (http://uk.php.net/manual/en/function.in-array.php#106319) states that some unusual results occur as a re

3条回答
  •  醉梦人生
    2020-12-18 08:03

    PHP treating arrays as primitive values is a constant source of pain as they can be very complex data structures, it doesn't make any sense. For example, if you assign array to something, and then modify the array, the original isn't modified, instead it is copied.

     NULL
    );
    
    
    
    var_dump( array() == NULL ); //True :(
    var_dump( in_array( array(), $arr ) ); //True, wtf? It's because apparently array() == NULL
    var_dump( in_array( new stdClass, $arr ) ); //False, thank god
    
    ?>
    

    Also, 'egg' is not a value in the array, it's a key, so of course it's surprising that it would return true. This kind of behavior is not ok in any other language I know about, so it will trip over many people who don't know php quirks inside out.

    Even a simple rule that an empty string is falsy, is violated in php:

    if( "0" ) {
    echo "hello"; //not executed
    }
    

    "0" is a non-empty string by any conceivable definition, yet it is a falsy value.

提交回复
热议问题