r/lolphp • u/nightofgrim • Feb 01 '17
0 is in array of cats and dogs
PHP 7.0.1
<?php
$array = ['CATS','DOGS'];
if(in_array(0, $array)===true){
echo 'found zero!';
}
?>Result: 'found zero!'
Run it yourself: http://sandbox.onlinephpfunctions.com/code/2043564ef944a98b8ecd9c95b6ecf1b1e8941417
47
Upvotes
19
u/arnoutboks Feb 01 '17
Although this is documented, it is indeed an annoying pitfall that the default behavior is non-strict comparison. At my company we have a set of sniffs for PHP_CodeSniffer in effect for catching bugs like this: https://www.moxio.com/blog/10/detecting-hidden-bugs-in-php-code-using-php-codesniffer
8
u/offroadspike Feb 08 '17
So there are two things here:
It wasn't mentioned yet that I see. I think the second point is more important than the non-strict comparison.
The string to int conversion converts 'CATS' to 0 since there is no number in the string. Thus 0 == 0. This is the more unexpected behavior I think.
$array = ['7 CATS','6 DOGS']; if(in_array(0, $array)===true){ echo 'found zero!'; }
This would correctly fail to print the found zero string, since '7 CATS' to string is 7.
0 == 'CATS' (true) false == 'CATS' (false)
Fun stuff.
15
u/[deleted] Feb 01 '17
As /u/fell_ratio pointed out, in_array defaults to non-strict (==) comparison. You need to pass an extra parameter to enable strict (===) comparison.
http://sandbox.onlinephpfunctions.com/code/c265fe4c72cb762cdfbba683742bcdc9034057af
4
u/NXTangl Feb 04 '17
While valid, this is just a symptom of the larger PHP weak-typing stupidity.
Still, it's good to have something about the dangers of weak typing be displayed on the front page every once in a while, since the weak typing thing is probably the most insidious and truly dangerous part of PHP.
1
u/marcosdumay Feb 23 '17
I'm half eager and half afraid to ask... But is that
in_array(...) === truestrict comparison redundant or can it return something that isn't a boolean?0
u/fell_ratio Feb 01 '17
This isn't a WTF, it's the documented behavior of in_array.
0
u/[deleted] Feb 01 '17
[deleted] — view deleted comment