PHP Operator Precedence
In this page:
Arithmetic Operator Precedence
PHP follows the same math convention you learned in school: * and / are evaluated before + and -, regardless of the order they're written in. 2 + 3 * 4 evaluates the multiplication first and gives 14, not 20 — parentheses are the only way to force a different order.
Example: Arithmetic Operator Precedence
<?php
echo 2 + 3 * 4;
?>
Login to try C/C++/Java/PHP code in the editor
Assignment Operator Precedence
Assignment operators sit near the bottom of PHP's precedence table and group right-to-left, which is exactly what makes a chain like $a = $b = $c = 0; work as expected — $c is assigned first, then that same value flows leftward into $b, then $a.
Example: Assignment Operator Precedence
<?php
$a = $b = $c = 0;
echo "$a $b $c";
?>
Login to try C/C++/Java/PHP code in the editor
Logical Operator Precedence
Comparison operators (>, ==, etc.) bind tighter than logical operators (&&, ||), so $age > 18 && $hasId is parsed as ($age > 18) && $hasId without needing explicit parentheses — the comparisons resolve to booleans first, and only then does the logical operator combine them.
Example: Logical Operator Precedence
<?php
$age = 20;
$hasId = true;
var_dump($age > 18 && $hasId);
?>
Login to try C/C++/Java/PHP code in the editor
and vs && Precedence
The word-form logical operators (and, or) have noticeably *lower* precedence than their symbolic counterparts (&&, ||) — low enough that $result = false or true; assigns false to $result, because = binds tighter than or. This exact gotcha is why most style guides steer people toward &&/|| in expressions.
Example: and vs && Precedence
<?php
$result = false or true;
var_dump($result);
?>
Login to try C/C++/Java/PHP code in the editor
Left-to-Right Associativity
When two operators share the same precedence level, PHP resolves them left to right — 10 - 3 - 2 evaluates as (10 - 3) - 2, giving 5, not 10 - (3 - 2). This left-to-right rule is what you fall back on any time precedence alone doesn't fully determine the order.
Example: Left-to-Right Associativity
<?php
echo 10 - 3 - 2;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: