Invalid PHP type variable

The most recent comment on the PHP help page in_array()( http://uk.php.net/manual/en/function.in-array.php#106319 ) indicates that some unusual results result from the PHP 'leniency to variable types', but gives no explanation why these results occur. In particular, I do not understand why this happens:

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking (this is the default, i.e. 3rd argument is false), return values are in comments
in_array(763, $array); // true
in_array('hhh', $array); // true

Or why did the poster think the following about strange behavior

in_array('egg', $array); // true
in_array(array(), $array); // true

(of course, an “egg” does occur in an array, and PHP does not care whether it is a key or value, and there is an array, and PHP does not care if it is empty or not?)

Can anyone point to pointers ..?

+5
source share
3 answers

, in_array() :

function in_array($needle, $haystack, $strict = FALSE) {
    foreach ($haystack as $key => $value) {
        if ($strict === FALSE) {
            if ($value == $needle) {
                return($key);
            }
        } else {
            if ($value === $needle) {
                return($key);
        }
    }
    return(FALSE);
}

, == - . , boolean TRUE, , , in_array, EXCEPT PHP typecast true:

'' == TRUE // false
0 == TRUE // false
FALSE == TRUE // false
array() == TRUE // false
'0' == TRUE // false

'a' == TRUE // true
1 == TRUE // true
'1' == TRUE // true
3.1415926 = TRUE // true
etc...

in_array . in_array === ==.

,

'a' === TRUE // FALSE
+1

763 == true, true , 0, NULL '', , ( ).

, TRUE, STRICT, , , is_rray ===, ,

763! == true

array()! == true

+4

PHP, , , , . , -, , , .

<?php

$arr = array(
    "key" => NULL
);



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

?>

, "egg" , , , , , true. , , , php quirks .

Even the simple rule that an empty string is false is broken in php:

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

"0" is a nonempty string by any conceivable definition, but this is a falsehood.

+1
source

All Articles