Description
While the operator precedence in PHP is clearly defined so that &&
has higher precedence than ||
and this precedence matches the vast majority of programming languages in use, expressions mixing those two operators without explicit parentheses still require the reader to know the precedence off the top of their head, adding room for error.
The coding style should require (or recommend) explicit parentheses whenever &&
and ||
are mixed within an expression to make the intent clear:
if ($foo && $bar || $baz) { } // no
if (($foo && $bar) || $baz) { } // yes
if ($foo && ($bar || $baz)) { } // yes, but different semantics than the "no".
The "Disjunctive Normal Form Types" RFC that is currently under discussion explicitly requires parentheses for types that mix union and intersection, likely for the same reason: Removing any possible ambiguity.
There's an open pull request for PHP_CodeSniffer that performs and highlights expressions where these operators are mixed without parentheses:
squizlabs/PHP_CodeSniffer#3205
Anecdotally running the Sniff from the PR on our code base exposed a non-trivial number of bugs where $foo && ($bar || $baz)
was intended, but $foo && $bar || $baz
was used, showing that this is an issue that happens in the real world.