php, my dearest old frienemy.
ok, so i can come to terms with why the string '0' would be a falsie value. that's only fair seeing as how '0'
is the same as 0
in a loosely typed language, and 0
is false
in a loosely typed language. so this gives that false
== 0
== '0'
.
fine fine... BUT!! what is this all about?
<?php
print "number of surprised persons: " . ('false' == 0);
the output is....
number of surprised persons: 1
how is this reasonable? am i the only one who's surprised by this? what am i failing to see?
further testing has proven that the integer 0 is equal (by operator ==) to
0 <-- integer
false <-- boolean
null <-- just.. you know, null
'0' <-- string
'' <-- string
'false' <-- string
'true' <-- string
'null' <-- string
naturally, i mostly use operator === to compare stuff. and now that i know about this, i'll have to adjust my programming of course, no question about that. but still! can someone shed some light pl0x?
It's because, when you compare a string to an integer, they don't both get converted to strings, or to booleans - they get converted to integers. For PHP, when you think about it, this isn't strange at all (comparatively, I suppose).
'true' == 0
// is the same as
(int)'true' == 0
// is the same as
0 == 0
// is the same as
true
And this is true for any non-numeric string as well as the string "0"
. The reason 1
is printed out is because the string version of true
is 1
(and the string version of false is an empty string).