Search code examples
phpcastingrangeassert

Why is assert of range( 0, 0 ) return true for any one-element array regardless of its value?


These are as expected (per https://php.net/manual/en/language.operators.array.php):

assert( range( 0, 0 ) == [0] );
assert( range( 0, 0 ) == ['0'] );
assert( range( 0, 0 ) !== ['not zero'] );
assert( range( 0, 1 ) != ['not zero', 'not zero'] );

But why is range( 0, 0 ) apparently considered == equal to any one-element array regardless of its value?

assert( range( 0, 0 ) == ['not zero'] ); // return TRUE??

Solution

  • Better explanation is the == operator convert the array element to int as the left side of the operator was array with int.

    Because both intval('not zero') and (int) 'not zero' will return 0 the compare will return true as it is 0 (as one can see here).

    When using === PHP is not doing type casting so the string stays string so the compare fails (from PHP operators):

    ===: TRUE if $a and $b have the same key/value pairs in the same order and of the same types.