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.
$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 evaluatesfalse || truefirst and assigns the result, so$fistrue.orhas lower precedence than=. PHP runs$t = falsefirst and then evaluatesor true, whose result is thrown away.$tstaysfalse.var_dump()shows both values with their types:bool(true)andbool(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.
Related articles
- loose comparison in a PHP switch: another case where PHP’s evaluation rules change the result

