The Analogy: The Auction Clerk's Settlement Sheet
Thursday is the store sale at the livestock mart, and behind the ring a clerk works a settlement pad. Each vendor gets one sheet, and the sheet is not blank paper. It is pre-printed with rows in a fixed order: hammer price at the top, then commission, then the insurance levy, then haulage, then a VAT row that applies only to the charges above it, and at the bottom the net figure that becomes a cheque. The clerk fills in numbers. The clerk does not decide the order.
That printed order is the whole point of the pad. A hundred years of arguments about whether the levy comes before or after commission, whether haulage is VATable, and whether the mart's percentage is taken off the gross or the net have been settled once and pressed into the paper. A new clerk on their first Thursday cannot get the sequence wrong, because the sequence is not theirs to choose. Two clerks working two different sheets for the same lot arrive at the same cheque, which is the only property anybody in the building actually cares about.
Where two rows sit at the same tier -- commission and levy are both percentages of the hammer price -- the clerk works down the column in the order printed, and it makes no difference to the answer because neither one feeds the other. When the auctioneer does want something out of sequence, for a vendor with a private haulage arrangement, they draw a bracket in the margin around two rows and write a subtotal beside it. That bracket outranks the printed order. It is the one mark on the sheet that says: do this bit first, then carry the result into the row below.
The failure mode is quiet and specific, and it is why the pad exists. A clerk who works the rows out of sequence does not produce a sheet that looks wrong. The columns still add up. The arithmetic in each row is still correct. If VAT gets calculated on the hammer price rather than on the charges, the sheet is internally consistent and the total is a plausible number in roughly the right range -- a hundred and fifty pounds wrong on a two-thousand-pound bullock. Nobody spots it at the ring. The vendor banks the cheque. It surfaces six weeks later in an audit, or it does not surface at all. PHP's operator precedence is that printed order, parentheses are the bracket in the margin, and a precedence mistake behaves exactly like the miscopied sheet: it runs, it produces a number, and the number is wrong.
Syntax or Core Structure
An operator is a symbol that takes one or two values and produces a third. PHP has arithmetic, string, assignment, comparison, logical, and bitwise families, and the ones you will type a hundred times a day are worth seeing side by side with their exact results rather than their descriptions.
<?php
declare(strict_types=1);
$a = 17;
$b = 5;
echo "sum : ", $a + $b, PHP_EOL;
echo "difference : ", $a - $b, PHP_EOL;
echo "product : ", $a * $b, PHP_EOL;
echo "quotient : ", $a / $b, PHP_EOL;
echo "intdiv : ", intdiv($a, $b), PHP_EOL;
echo "remainder : ", $a % $b, PHP_EOL;
echo "power : ", $a ** 2, PHP_EOL;
echo "concat : ", "lot " . $a, PHP_EOL;
$total = 0;
$total += $a;
$total *= 2;
$total -= $b;
echo "compound : {$total}", PHP_EOL;
$label = "lot";
$label .= " " . $a;
echo "appended : {$label}", PHP_EOL;
var_dump($a > $b, $a == "17", $a === "17", $a <=> $b);
Output:
sum : 22
difference : 12
product : 85
quotient : 3.4
intdiv : 3
remainder : 2
power : 289
concat : lot 17
compound : 29
appended : lot 17
bool(true)
bool(true)
bool(false)
int(1)
Three results in there are worth stopping on. $a / $b printed 3.4, not 3: division in PHP produces a float whenever the operands do not divide evenly, so if you want the whole number of times five goes into seventeen you ask for intdiv and if you want what is left over you ask for %. The compound operators are not shorthand for a different operation; $total += $a is exactly $total = $total + $a, and .= is the same trick for strings. And $a <=> $b returned int(1), because the spaceship operator answers "which side is bigger" as a number you can hand straight to a sort function instead of a boolean you would have to unpack.
Technical Depth: The Printed Order Of The Rows
The full precedence table, tightest first
Everything below binds more loosely than the line above it. You do not need to memorise this, but you do need to know that it exists and roughly where the cliffs are, because PHP will never warn you that you meant a different tier.
| Tier | Operators | Associativity |
|---|---|---|
| 1 (tightest) | clone, new | none |
| 2 | ** | right |
| 3 | unary + -, ++, --, ~, casts such as (int), @ | right |
| 4 | instanceof | none |
| 5 | ! | right |
| 6 | * / % | left |
| 7 | binary + - | left |
| 8 | << >> | left |
| 9 | . -- moved below arithmetic in PHP 8 | left |
| 10 | < <= > >= | none |
| 11 | == != === !== <=> | none |
| 12 | & bitwise and | left |
| 13 | ^ bitwise xor | left |
| 14 | bitwise or, written as one vertical bar | left |
| 15 | && | left |
| 16 | logical or, written as two vertical bars | left |
| 17 | ?? | right |
| 18 | the ternary ? : | none in PHP 8 |
| 19 | = and every compound assignment | right |
| 20 | yield from, yield, print | none |
| 21 | and | left |
| 22 | xor | left |
| 23 (loosest) | or | left |
Two rows in that table are the ones that break real programs. Tier 19 sits below the comparison and logical tiers but above tiers 21 to 23, which is why and and or are not interchangeable with && and the double bar. And tier 9 changed in PHP 8: concatenation used to bind as tightly as addition, and now it binds more loosely, which silently changed the meaning of some perfectly ordinary lines.
Integer division, remainder and the sign rule
Money and quantities live in integers, so the exact behaviour of the three division operators is not trivia. Note especially that truncation goes toward zero rather than downward, which is the opposite of what several other languages do.
| Expression | Result | Rule |
|---|---|---|
intdiv(7, 3) | 2 | truncates toward zero |
intdiv(-7, 3) | -2 | still toward zero, not down to -3 |
7 % 3 | 1 | sign follows the left operand |
-7 % 3 | -1 | sign follows the left operand |
7 % -3 | 1 | the right operand's sign is discarded |
6 / 3 | int(2) | int when both are ints and it divides evenly |
7 / 3 | a float | printed digits depend on the precision ini setting |
intdiv(1, 0) | throws | DivisionByZeroError |
1 % 0 | throws | DivisionByZeroError |
1 / 0 | throws | DivisionByZeroError since PHP 8; it used to warn |
fdiv(1, 0) | INF | the one division that never throws |
The assignment and null-handling family
Compound assignment is pure shorthand, which means a compound operator can never do something its long form could not. The null operators are the exception worth learning properly, because two of them look interchangeable and are not.
| Written | Equivalent to | Note |
|---|---|---|
$x += 3 | $x = $x + 3 | same for -=, *=, /=, %=, **= |
$s .= "x" | $s = $s . "x" | the only string assignment operator |
$x ??= 5 | $x = $x ?? 5 | assigns only when $x is null or not set |
$x ?? 5 | no long form | null-safe, and silent on an undefined variable |
$x ?: 5 | $x ? $x : 5 | falls back on any falsy value, including 0 |
$f &= ~4 | $f = $f & ~4 | clears the third bit and leaves the rest |
The difference in those last two rows is a real bug generator. $page = $_GET['page'] ?: 1; turns a legitimate page 0 into page 1 and raises a warning when the key is absent, while $page = $_GET['page'] ?? 1; does neither.
The cliffs, demonstrated
Every line below is a precedence question with a surprising answer, and each one has cost somebody an afternoon.
<?php
declare(strict_types=1);
echo -3 ** 2, PHP_EOL;
echo 2 ** 3 ** 2, PHP_EOL;
echo "sum: " . 1 + 2, PHP_EOL;
var_dump(10 / 5);
var_dump(10 / 4);
var_dump(-7 % 3, 7 % -3);
var_dump(intdiv(-7, 3));
$flags = 0;
$flags |= 1 << 2;
$flags |= 1 << 5;
echo $flags, PHP_EOL;
var_dump(($flags & (1 << 2)) !== 0);
$x = true and false;
var_dump($x);
Output:
-9
512
sum: 3
int(2)
float(2.5)
int(-1)
int(1)
int(-2)
36
bool(true)
bool(true)
Read those in pairs. -3 ** 2 is -9 because ** sits at tier 2 and the unary minus at tier 3, so PHP squares three and then negates it; if you want nine you write (-3) ** 2. 2 ** 3 ** 2 is 512 and not 64 because ** is right-associative, so it is 2 ** 9. "sum: " . 1 + 2 prints sum: 3 under PHP 8 and printed 2 under PHP 7, where concatenation bound tighter and the engine added two to the string "sum: 1". 10 / 5 is genuinely int(2) while 10 / 4 is float(2.5), so the return type of / depends on the values, not the types. And the last pair is the famous one: $x = true and false binds as ($x = true) and false, because = at tier 19 outranks and at tier 21, so $x is true and the false is evaluated and thrown away.
Real World Example: The Vendor Settlement Sheet
Here is the clerk's pad in code. Every rate is an integer number of basis points, every amount is an integer number of pence, and the order of the rows is written into the sequence of statements rather than left to whoever reads the file next. The only floats in the program appear inside number_format at the moment of printing, which is the last possible moment and the only safe one.
<?php
declare(strict_types=1);
const COMMISSION_BP = 450; // 4.50 per cent of the hammer price
const LEVY_BP = 35; // 0.35 per cent insurance levy
const VAT_BP = 2000; // 20 per cent, on the charges only
const HAULAGE_PENCE = 1250; // flat, per lot
/** Take a rate expressed in basis points off an amount in pence. */
function basisPoints(int $pence, int $rate): int
{
return intdiv($pence * $rate, 10000);
}
$lots = [
[12, "Limousin heifer", 148000],
[13, "Charolais bull", 236500],
[14, "Store lambs x9", 61200],
[15, "Angus steer", 129950],
];
$rule = str_repeat("=", 58);
$thin = str_repeat("-", 58);
echo "THURSDAY STORE SALE -- VENDOR SETTLEMENT", PHP_EOL;
echo $rule, PHP_EOL;
printf("%-3s %-17s %9s %8s %6s %10s\n", "LOT", "DESCRIPTION", "HAMMER", "CHARGES", "VAT", "NET");
echo $thin, PHP_EOL;
$totals = ['hammer' => 0, 'charges' => 0, 'vat' => 0, 'net' => 0];
foreach ($lots as [$lot, $beast, $hammer]) {
$commission = basisPoints($hammer, COMMISSION_BP);
$levy = basisPoints($hammer, LEVY_BP);
$charges = $commission + $levy + HAULAGE_PENCE;
$vat = basisPoints($charges, VAT_BP);
$net = $hammer - $charges - $vat;
$totals['hammer'] += $hammer;
$totals['charges'] += $charges;
$totals['vat'] += $vat;
$totals['net'] += $net;
printf(
"%-3d %-17s %9s %8s %6s %10s\n",
$lot,
$beast,
number_format($hammer / 100, 2),
number_format($charges / 100, 2),
number_format($vat / 100, 2),
number_format($net / 100, 2)
);
}
echo $thin, PHP_EOL;
printf(
"%-21s %9s %8s %6s %10s\n",
count($lots) . " lots",
number_format($totals['hammer'] / 100, 2),
number_format($totals['charges'] / 100, 2),
number_format($totals['vat'] / 100, 2),
number_format($totals['net'] / 100, 2)
);
echo $rule, PHP_EOL;
printf(
"commission %s%% levy %s%% haulage %s per lot\n",
number_format(COMMISSION_BP / 100, 2),
number_format(LEVY_BP / 100, 2),
number_format(HAULAGE_PENCE / 100, 2)
);
printf("vat is charged on the charges column only, at %d%%\n", intdiv(VAT_BP, 100));
printf("cheque total to vendors: %s\n", number_format($totals['net'] / 100, 2));
printf("retained by the mart: %s\n", number_format(($totals['charges'] + $totals['vat']) / 100, 2));
$balances = $totals['hammer'] === $totals['net'] + $totals['charges'] + $totals['vat'];
printf("cross-check: %s\n", $balances ? "balances" : "DOES NOT BALANCE");
Output:
THURSDAY STORE SALE -- VENDOR SETTLEMENT
==========================================================
LOT DESCRIPTION HAMMER CHARGES VAT NET
----------------------------------------------------------
12 Limousin heifer 1,480.00 84.28 16.85 1,378.87
13 Charolais bull 2,365.00 127.19 25.43 2,212.38
14 Store lambs x9 612.00 42.18 8.43 561.39
15 Angus steer 1,299.50 75.51 15.10 1,208.89
----------------------------------------------------------
4 lots 5,756.50 329.16 65.81 5,361.53
==========================================================
commission 4.50% levy 0.35% haulage 12.50 per lot
vat is charged on the charges column only, at 20%
cheque total to vendors: 5,361.53
retained by the mart: 394.97
cross-check: balances
The cross-check line is the reason to write it this way. $totals['hammer'] === $totals['net'] + $totals['charges'] + $totals['vat'] relies on precedence rather than fighting it: addition at tier 7 binds tighter than the identity test at tier 11, so the three parts are summed and then compared, and no parentheses are needed. Because every figure is an integer number of pence, that comparison is exact -- === on integers means what it says. Write the same program with float pounds and the check fails on some Thursdays and passes on others, and you will spend a day discovering that 1480.00 - 84.28 - 16.85 is not quite 1378.87 in binary floating point.
The basisPoints helper carries the rounding rule, and it carries it in one place. intdiv($pence * $rate, 10000) multiplies first and divides once, so the two operations happen in the order the operator table promises and no intermediate value is ever fractional. Compare it with the obvious-looking (int) ($pence * ($rate / 10000)), which computes a float percentage, multiplies a float by an integer, and then truncates -- three chances for a value like 6659.999999999999 to appear and become 6659. The percentages in the footer are printed by dividing basis points by a hundred, so 450 becomes 4.50 for a human without ever having been a float in the arithmetic.
Look at what the column widths encode. The format string %-3d %-17s %9s %8s %6s %10s adds up to fifty-eight characters, which is exactly the length of the two rules, and the totals row merges the first two fields into a single %-21s so it still lines up. That is not decoration: a settlement sheet that a vendor cannot read down a column is a settlement sheet that generates phone calls. The - flag left-justifies text and its absence right-justifies numbers, which is the convention every printed ledger in the world already uses, and number_format supplies the thousands separators so that 5,756.50 cannot be misread as 575.65.
Now the flaws, because this program has real ones. VAT is charged on the charges column only, which the footer states, but nothing in the code enforces the claim -- if a later maintainer adds a taxable row above the VAT line and forgets to include it in $charges, the sheet will still balance and will still be wrong, which is the miscopied-pad failure exactly. intdiv truncates every rate calculation toward zero, so the mart loses a fraction of a penny on most lots and the vendor gains it; that is a commercial decision that no comment in the file admits to making. The lot data is a hardcoded array of positional triples, so [12, "Limousin heifer", 148000] gives no protection at all against somebody swapping the lot number and the price -- both are integers and both would pass. And $hammer is trusted without validation, so a negative hammer price would produce a negative commission, a negative VAT, and a cheerful balances on a sheet that says the mart owes the vendor money for taking the animal away.
Common Mistakes
- Using
andororinside an assignment.$ok = doThing() or die("failed");binds as($ok = doThing()) or die(...), so$okgets the function's return value and thedieonly fires when that value is falsy -- which is sometimes what you wanted and never what you wrote. Use&&and the double bar for logic and reserve the word forms for the one idiom they suit, a standalone$conn = connect() or die();statement you are about to delete anyway. - Reading
-3 ** 2as nine.**binds tighter than the unary minus, so PHP squares three and negates the result:-9. Any time a negative base is raised to a power, write the parentheses --(-3) ** 2-- because the reader cannot be expected to recall tier 2 from tier 3. - Expecting
/to give you a whole number.$perPage = $total / $pagesproduces a float the moment the division is uneven, and passing that float into a function typedintunderstrict_types=1throws aTypeErrorat the call site rather than where the division happened. Useintdivwhen you mean integer division and%when you want the remainder. - Chaining ternaries without parentheses.
$grade = $n > 90 ? "A" : $n > 80 ? "B" : "C";was ambiguous and left-associative in PHP 7 and is a compile-time error in PHP 8, so the file will not run at all. Add the parentheses, or better, usematch (true)which reads top to bottom the way you already think about it. - Using
?:where you meant??. The short ternary tests truthiness, so$qty = $input ?: 1turns a deliberate0into1and a deliberate""into1, and it raises a warning if the variable does not exist.??tests only for null and is silent on undefined keys, which is what you want at every request boundary. - Assuming concatenation still binds like addition.
echo "total: " . $a + $b;printed a bare number under PHP 7 and prints the sentence with the sum under PHP 8. Code that was written to exploit the old behaviour changed meaning without changing a character, so never rely on the tier of.-- parenthesise the arithmetic. - Writing
$flags & 4 == 4. Comparison sits at tier 11 and bitwise and at tier 12, so PHP evaluates4 == 4first and then computes$flags & true, which is$flags & 1-- a test of the wrong bit that returns a plausible boolean. The parentheses are mandatory:($flags & 4) === 4. - Using
%to wrap an index around.$next = ($i - 1) % count($items);gives-1when$iis zero, because the remainder takes the sign of the left operand, and a negative offset is not the last element in PHP the way it is in some other languages. Add the modulus first:($i - 1 + $n) % $n. - Putting an assignment in a condition.
if ($status = "active")assigns and then tests, so it is true forever and it silently overwrites$status. This is not caught by anything -- it is a legal expression -- so the only defence is the habit of reading every=inside anifas a bug until proven otherwise.
Best Practices
- Parenthesise anything a reader would have to look up. The precedence table is correct and nobody has it memorised.
($flags & self::ARCHIVED) !== 0costs two characters more than the version that relies on tiers 11 and 12 and saves the next person a trip to the manual. - Use
&&and the double bar for all logic. Keepand,or, andxorout of the codebase entirely; their only distinguishing feature is a precedence that surprises people, and a linter rule banning them costs nothing. - Say which division you mean.
intdivfor whole units,%for the remainder,fdivwhen you deliberately want infinity instead of an exception, and plain/only when a float result is genuinely the answer. The choice belongs in the code, not in the reader's head. - Keep rates in basis points and amounts in the smallest unit.
intdiv($pence * $rateBp, 10000)never produces a fractional intermediate, so the rounding happens once, in a place you chose, under a rule you can write down. Percentages as floats put the rounding somewhere between the multiply and the cast. - Reach for
??and??=at boundaries, andmatchinstead of stacked ternaries. Both replace a precedence question with a construct that has only one reading, andmatchalso gives you anUnhandledMatchErrorinstead of a silently wrong fallthrough. - Never mix
+and array union in the same mental breath.$a + $bon arrays keeps the left-hand value for any duplicate key and does not renumber, whilearray_mergerenumbers integer keys and lets the right-hand side win. They are different operations that share a symbol; writearray_mergeorarray_replacewhen that is what you mean. - Put a cross-check at the end of any money calculation. One
===comparing the gross against the sum of its parts catches transposed rows, missed columns, and the maintainer who adds a charge in the wrong place. It only works because integers compare exactly, which is the other reason not to use floats. - Let a formatter and a static analyser hold the line. PHP-CS-Fixer will space your binary operators consistently so that
-3 ** 2at least looks like the surprise it is, and PHPStan flags the assignment-in-condition and the always-true comparison before a reviewer has to.
Practice Exercises
- Predict, then run. Write down your expected output for these six lines before executing them:
-2 ** 3,2 ** 2 ** 3,10 % -4,intdiv(-10, 4),"n: " . 2 * 3, andvar_dump(9 / 3). Run them, and for every line you got wrong, find the tier in the precedence table that explains it and write the tier number in a comment. - Break the settlement sheet on purpose. Take the auction program and change
$vat = basisPoints($charges, VAT_BP)to charge VAT on the hammer price instead. Note that the cross-check still saysbalances, then work out what extra assertion would have caught it and add that assertion. This is the miscopied-pad failure in miniature. - Write a flags register. Define four permission constants as
1 << 0through1 << 3, then writegrant,revoke, andhasfunctions using bitwise and, bitwise or, and~. Print the integer value of the register after each operation as both a decimal and astr_pad(decbin($f), 4, "0", STR_PAD_LEFT)string, and deliberately write one test as$f & PERM == PERMto see the wrong answer for yourself. - Replace a ternary chain. Find or invent a five-branch nested ternary, confirm that PHP 8 refuses to compile it, then rewrite it twice: once with explicit parentheses and once with
match (true). Compare the two for length and for how easy it is to add a sixth branch, and note which version you would want to be looking at during an incident.