Can someone explain me why this:
var_dump((bool) 1==2);
returns
bool(true)
but
var_dump(1==2);
returns
bool(false)
Of course the second return is correct, but why in the first occasion php returns an unexpected value?
Can someone explain me why this:
var_dump((bool) 1==2);
returns
bool(true)
but
var_dump(1==2);
returns
bool(false)
Of course the second return is correct, but why in the first occasion php returns an unexpected value?
The way you have written the statement ((bool) 1==2) will always return true because it will always execute the code like below flow:
First, it will execute
and (bool) 1 will return true.
Now since (bool)1 is true at second step your statement will be like
Since if we will typecast 2 into boolean it will return true, at final state your statement will be like
Which will obviously return true. The same thing I have explained year back in my post PHP Type casting as well.
It's actually not as strange it seems.
(bool)
has higher precedence than==
, so this:is equivalent to this:
or this:
Due to type juggling, the
2
also essentially gets cast tobool
(since this is a "loose comparison"), so it's equivalent to this:or this:
I use this way:
Because in the first example, the cast takes place before the comparison. So it's as if you wrote
which is equivalent to
which is evaluated by converting
2
totrue
and comparing, ultimately producingtrue
.To see the expected result you need to add parens to make the order explicit:
See it in action.