Why do these 2 statements not output the same result?
The only reason I can imagine is operator precedence which appears to the same for ==
and ===
.
$a = (bool) 4 == 4;
$b = (bool) 4 === 4;
var_dump($a); // bool(true)
var_dump($b); // bool(false)
Yes, operator precedence is the same for ==
and ===
. Clearly the difference here is the operator itself.
First we have to acknowledge that type casting has a higher precedence than these two comparison operators. So, in reality, you're doing:
$a = (TRUE == 4);
$b = (TRUE === 4);
When you do a ==
you're simply trying to see if the values are equal. Only values of the same type can be compared. Since you start with a boolean, the number 4 will therefore also be turned into a boolean. This is called type juggling. We already know that (bool)4
is TRUE
. So $a
must be TRUE
.
However, when you do a ===
there is no type juggling, instead it will only return TRUE
if the two operands have the same value and type. Since a boolean isn't the same type as an integer $b
must be FALSE
.