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....
开发者_JAVA技巧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).
As far as you're concerned about the output:
('false' == 0)
= boolean TRUE
= string "1"
.
echo
is triggering string context.
But from your comment below I've just seen, that you'd like to learn more about the comparison. Take a look what you do:
Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type juggling.
so you are doing a non-strict comparison of a number with a string:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. (REF)
Note: Number, not integer as written in the accepted answer:
<?php
print "number of surprised persons: " . ('false' == 0.3 - 0.2 - 0.1);
Have fun.
false == 0 is true. True as a string is '1' and you are doing an implicit conversion when you interpolate the value.
$a = true;
echo "$a"; #1
You can find a PHP truth table here. I would just recommend the === comparator unless you have a good reason to use ==
http://php.net/manual/en/types.comparisons.php
精彩评论