Last Updated: September 09, 2019
·
749
· daraff

The PHP Type System can Shoot you in the Leg

Recently i found a bug in our tests, where we compare 2 json files recursively value by value.
Even when the two json files were not the same, the tests returned true.
After debugging some time i found out the reason:

I will show you some examples:

in_array(0, array(18));      // FALSE
in_array(0, array('18'));    // FALSE
in_array(0, array('Foo'));   // TRUE

Why you get back TRUE in the last example?
The reason is the string-to-number conversions (http://php.net/manual/en/language.types.string.php#language.types.string.conversion). If we attempt to get a number from 'Foo', we get back 0.

echo intval('Foo');  // 0

To avoid this, provide the third paramter, true, placing the comparison in strict mode, which will not only compare values, but types as well:

in_array(0, array('Foo'), true);   // FALSE

2 Responses
Add your response

I don't think this is a bug. You are comparing a number.
It is like:

if( 0 == 'Foo' ) // it return TRUE

but if it was a string on both end:

if( '0' == 'Foo' ) // it return FALSE

over 1 year ago ·

Yes, it's not a bug in PHP, it's the defined type comparison behaviour. But our integration tests throwed back a wrong result, based on this missunderstanding of type comparison.

over 1 year ago ·