Operator Precedence In PHP

Quick Summary

  • Operator precedence sets how tightly operators bind, so multiplication runs before addition unless parentheses force a different order.
  • The || operator binds tighter than =, but or binds looser, so $t = false or true leaves $t set to false.
  • Use || and && when assigning a condition's result, or wrap the whole expression in parentheses to get the intended value.

The precedence of an operator specifies how tightly it binds two expressions together. In 1 + 5 * 3 the answer is 16, not 18, because the multiplication operator (*) has higher precedence than the addition operator (+). Parentheses force a different order when you need one: (1 + 5) * 3 evaluates to 18.

Precedence gets tricky with PHP’s logical operators, because || and or (and likewise && and and) do the same job but have different precedence.

PHP
$f = false || true; // true --> because (false || true) = true ... and  '||' has higher Precedence than '='
$t = false or true; // false --> because 'or' has lower Precedence that '='. so it basically assign false into  $t

var_dump($f,$t);

How it works

  • || has higher precedence than the assignment operator =. PHP evaluates false || true first and assigns the result, so $f is true.
  • or has lower precedence than =. PHP runs $t = false first and then evaluates or true, whose result is thrown away. $t stays false.
  • var_dump() shows both values with their types: bool(true) and bool(false).

The same trap applies to and: $x = true and false; leaves $x set to true.

How to avoid it

Use || and && when you assign the result of a condition, or wrap the whole expression in parentheses, as in $t = (false or true);. Parentheses also fix a nested ternary operator that PHP would otherwise group the wrong way. The low precedence of or is also what makes the old do_something() or die() pattern work: the call runs first, and die() only runs if it returns a falsy value.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More