as I know false is a 0
if(-1 > false)
print "Here";
in this code if returns a true and here
is printed
WHY ?
as I know false is a 0
if(-1 > false)
print "Here";
in this code if returns a true and here
is printed
Please see PHP Comparision Operators - table Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result
bool or null anything Convert both sides to bool, FALSE < TRUE
So if you compare bool to anything else, then the second operand is casted to boolean true.
Also we have information here, that FALSE < TRUE
, what exactly happens in your example.
In this case it's -1
that is converted into boolean (true
, as only 0
is treated as false
). So the final comparison is
if (true > false) {
...
}
Type Juggling can be very unintuitive, so always try to avoid situations where you compare variables of two different types. In case of equality comparison always try to use identity operator (===
), in case of inequality all you can do is to add a manual cast.
See also: http://us3.php.net/manual/en/types.comparisons.php
<
is a numerical comparison operator, the code does loose comparison converting -1
to true and hence the result.
WARNING: -1 is considered TRUE, like any other non-zero
(whether negative or positive) number!
Check with this two code. You can get the difference
if(-1 > false)
print "Here"; //This will print the `Here`
if(-1 > 0)
print "Here"; // Not print `Here`