I have a codebase where developers decided to use AND
and OR
instead of &&
and ||
.
I know that there is a difference in operators' precedence (&&
goes before and
), but with the given framework (PrestaShop to be precise) it is clearly not a reason.
Which version are you using? Is and
more readable than &&
? Or is there no difference?
Another nice example using
if
statements without=
assignment operations.and
because
AND
has a lower precedence and thus||
a higher precedence.These are different in the cases of
true, false, false
andtrue, true, false
. See https://ideone.com/lsqovs for en elaborate example.Precedence differs between && and and (&& has higher precedence than and), something that causes confusion when combined with a ternary operator. For instance,
will return a string whereas
will return a boolean.
"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.
The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
Mixing them together in single operation, could give you unexpected results in some cases I recommend always using &&, but that's your choice.
On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.
Example if you do (14 & 7) the result would be 6.
Here's a little counter example:
output:
I'd say this kind of typo is far more likely to cause insidious problems (in much the same way as
=
vs==
) and is far less likely to be noticed thanadn
/ro
typos which will flag as syntax errors. I also find and/or is much easier to read. FWIW, most PHP frameworks that express a preference (most don't) specify and/or. I've also never run into a real, non-contrived case where it would have mattered.If you use
AND
andOR
, you'll eventually get tripped up by something like this:Want to guess what
$truthiness
equals?If you said
false
... bzzzt, sorry, wrong!$truthiness
above has the valuetrue
. Why?=
has a higher precedence thanand
. The addition of parentheses to show the implicit order makes this clearer:If you used
&&
instead ofand
in the first code example, it would work as expected and befalse
.As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than
=
: