2 minutes
Logical Operator and Operator Precedence
@MichalBundyra tweeted yesterday:
TIL && and AND are not the same… https://3v4l.org/dVVYc Thanks @geerteltink
Honestly, I never use(d) and
. But it is interesting to learn that there is an actual difference and not just a flavor.
Michal compares the output of and
and &&
.
<?php
$a = 2 and 3;
$b = 2 && 3;
var_dump($a, $b);
Result
int(2)
bool(true)
Wait what?
Logical Operator “and” and “&&” are not identical
Logical Operators
The documentation for the Logical Operators states:
The reason for the two different variations of “and” and “or” operators is that they operate at different precedences. (See Operator Precedence.)
Short-circuiting operators
<?php
// foo() will never get called as those operators are short-circuited
$a = (false && foo());
$b = (false and foo());
var_dump($a, $b);
Result
bool(false)
bool(false)
“&&” has a greater precedence than “and”
<?php
// The result of the expression (true && false) is assigned to $c
// Acts like: ($c = (true && false))
$c = true && false;
// The constant true is assigned to $d before the "and" operation occurs
// Acts like: (($d = true) and false)
$d = true and false;
var_dump($c, $d);
Result
bool(false)
bool(true)
Operator Precedence
Furthermore, the documentation for Operator Precedence suggests the usage of parentheses to improve readability.
The precedence of an operator specifies how “tightly” it binds two expressions together.
[..]
Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
Conclusion
So, and
can lead to unexpected results (unless you really know how it works). On the top of my head, I cannot think of a scenario, where and
would be required.
To prevent unwanted surprises, one can either put and
comparison in parentheses or even better use the &&
operator.
<?php
$a = (2 and 3);
$b = 2 && 3;
var_dump($a, $b);
Result
bool(true)
bool(true)