In PHP 7, the following snippet strangely prints true
:
$b = true and false;
var_dump($b);
However, if I cast it, it correctly prints false
:
$b = (bool)(true and false);
var_dump($b);
What is the phenomenon that causes this to happen?
It's not the cast that's doing it, it's the parentheses. and
has lower precedence than =
, so your first statement is treated as
($b = true) and false;
You need to write:
$b = (true and false);
or
$b = true && false;
&&
and and
are equivalent except for their precedence (the same goes for ||
and or
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With