When an expression has several operators, PHP follows an order of priority called precedence. You know it from maths: multiplication comes before addition.
<?php
echo 2 + 3 * 4;
14
3 * 4 runs first, then + 2.
A simplified order, highest first
**(power)++--and casts like(int)!(not)*/%+-.(concatenation, since PHP 8)<<=>>===!====!==<=>&&||??? :(ternary)=+=-=and other assignmentsandxoror
You do not need to memorise this. Use it when something behaves unexpectedly.
Common surprises
<?php
var_dump(true || false && false); // && is stronger than ||
var_dump((true || false) && false);
bool(true)
bool(false)
<?php
echo -2 ** 2; // power is stronger than minus
echo "\n";
echo (-2) ** 2;
-4
4
<?php
echo "Sum: " . 1 + 2; // in PHP 8, + comes before the dot
Sum: 3
Same level: which side first?
Most operators with the same priority run left to right. A few run right to left: **, assignment and ??.
<?php
echo 2 ** 3 ** 2 . "\n"; // 2 ** (3 ** 2)
echo 10 - 4 - 3; // (10 - 4) - 3
512
3
The practical rule
Add brackets whenever there is any doubt. Brackets cost nothing, and they tell the next reader exactly what you meant.
<?php
$price = 100;
$discount = 20;
$tax = 18;
$total = ($price - $discount) * (1 + $tax / 100);
echo $total;
94.4
Brackets are not a sign of weakness
&& and || expressions. It is clearer, and it avoids a whole family of bugs.