Home » Php » if statement – PHP conditional logic AND OR

if statement – PHP conditional logic AND OR

Posted by: admin February 25, 2020 Leave a comment

Questions:

small question. I have this code:

if($A || $B && $C)

This results in

if (($A) || ($B && $C))

Since AND has a higher precedence, i expected:

if (($A && $C) || ($B && $C))

Why is this not the case? Thanks

How to&Answers:

For less confusion, you can replace the && and || operators respectively by multiply and add operators, they have the same predecence.

The logical operation $A || $B && $C could be translated in mathematical as $A + $B * $C (This is definitely not the same operation, but the predecence is similar)

You can’t refactorize $A + $B * $C to $A * $C + $B * $C, however, you can rephrase the operation to ($A) + ($B * $C)

Answer:

&& has a higher priority than ||

If you have a look into operator precedence you’ll see that && has a higher priority than ||, however quoting from this documentation:

Parentheses may be used to force precedence, if necessary.

So if you just use the code you expected instead, this’ll give you the results you want:

if (($A && $C) || ($B && $C))