0

as I know false is a 0

if(-1 > false)
    print "Here";

in this code if returns a true and here is printed


WHY ?
Anri
  • 1,706
  • 2
  • 17
  • 36

4 Answers4

2

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.

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
1

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

Crozin
  • 43,890
  • 13
  • 88
  • 135
1

< is a numerical comparison operator, the code does loose comparison converting -1 to true and hence the result.

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1
 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` 
Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25