Making sense of inequality comparisons between a number and a boolean

93 views Asked by At

The type comparison chart in PHP documentation shows the result of both strict === and loose == comparisons. There is nothing about inequality comparisons:

true < 0 => false
0 < true => true
true < 1 => false
1 < true => false
true < -1 => false
-1 < true => false

false < 0 => false
0 < false => false
false < 1 => true
1 < false => false
false < -1 => true
-1 < false => false

Can someone rationalize the above results?

2

There are 2 answers

5
AudioBubble On

when converting booleans to integer, the true will be converted to 1 and false to 0

From PHP Manual: http://php.net/manual/en/language.types.integer.php

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

Also:

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

true  < 0 => false => true < (bool)(0) => true < false => 1 < 0 = false
0 < true => true  => (bool)(0) < true => false < true => 0 < 1 = true
true < 1 => false => true < (bool)(1) => true < true => 1 < 1 = false
1 < true => false => (bool)(1) < true => => true < true => 1 < 1 = false
true < -1 => false => true < (bool)(-1) => true < true => 1 < 1 = false
-1 < true => false => (bool)(-1) < true => true < true = > 1 < 1 = false

false < 0 => false => false < (bool)(0) => false < false => 0 < 0 = false
0 < false => false => (bool)(0) < false => false < false => 0 < 0 = false
false < 1 => true => false < (bool)(1) => false < true => 0 < 1 = true
1 < false => false => (bool)(1) < false => true < false => 1 < 0 = false
false < -1 => true => false < (bool)(-1) => false < true => 0 < 1 = true
-1 < false => false => (bool)(-1) <  false => true < false => 1 < 0 =  false
1
Sujit Patil On

true < 0 => false ===> 1 < 0 => false (0==0 ==>true )
0 < true => true ===> 0 < 1 => true
true < 1 => false ===> 1 < 1 => false (1==1 ==>true )
1 < true => false ===> 1 < 1 => false (1==1 ==>true )
true < -1 => false ===> 1 < -1 => false
-1 < true => false ===> -1 < 1 => false ======> 1 < 1 => false (boolean type is treated as unsigned)
===> false < 0 => false ===> 0 < 0 => false
0 < false => false ===> 0 < 0 => false
false < 1 => true ===> 0 < 1 => true
1 < false => false ===> 1 < 0 => false
false < -1 => true ===> 0 < -1 => true ======> 0 < 1 => true(boolean type is treated as unsigned)
-1 < false => false ===> -1 < 0 => false ======> 1 < 0=> false(boolean type is treated as unsigned)