The Analogy: The Signal Box At The Junction
Stand in the signal box above a busy railway junction and you are watching a machine whose entire job is to decide. A train is approaching from the up main line; ahead of it the rails split three ways -- the fast line to the city, the slow line through the goods yard, and a dead-end bay platform for terminating services. The signalman does not move the train. He reads a few facts about it -- its class, whether it is carrying the single-line token, whether the box ahead has accepted it -- and on those facts he pulls the levers that set the points and clear or hold the signals. The train then goes where the levers sent it. That is a conditional: a small amount of reading, a decision, and exactly one path taken out of several that were possible.
The levers are not independent. Underneath the floor of the box runs the interlocking frame, a bed of steel bars and tappets that physically prevents the signalman from pulling two levers that would send trains into each other. If the points are set for the fast line, the bar under the slow-line signal lever is locked solid and will not move. This is the difference between a heap of separate if statements, each free to fire on its own, and a single structure -- a match, a well-formed if/elseif/else chain -- where the branches are mutually exclusive by construction. The interlocking is what lets the signalman work a hundred trains an hour without stopping to reason about every combination: the frame has already ruled out the impossible ones.
The signalman also has a standing rule for the case he did not plan for. A train arrives that is not booked in the working timetable -- an unscheduled charter, an engineering movement, a locomotive running light. He does not freeze. The rule book says where such a movement goes by default: into the bay platform, held, until control tells him otherwise. Every real decision needs that final arm, the else or the default, because the world sends inputs the timetable never mentioned, and a junction with no plan for the unexpected train is a junction that stops working the first time one appears.
The failure that the interlocking is built to prevent is the false clear: a signal showing green for a route that is not actually safe, because two decisions were made separately and nobody checked they agreed. In a signal box this is a collision. In code it is the bug where one if sets a flag and a later, unrelated if reads a stale copy of it, or where a switch falls through a missing break into the next case, or where a loose == comparison quietly treats the string "free" as equal to zero and clears a train that should have been held. The whole of this lesson is about writing decisions whose branches interlock, so that exactly one path is taken, the unexpected input has somewhere to go, and no comparison clears a route it should not.
Syntax or Core Structure
PHP offers a graded set of decision tools, from the plain if up to the PHP 8 match expression. The first thing to see is that some of them are statements -- they run code -- and some are expressions -- they produce a value you can assign. Getting that distinction right removes most of the awkwardness people feel with ternaries and match.
<?php
declare(strict_types=1);
// A statement chain: elseif rungs are tried top to bottom, first hit wins.
$platform = ['express' => 1, 'stopper' => 3, 'freight' => 5, 'empty' => 7];
$class = 'express';
echo "class {$class} to platform {$platform[$class]}", PHP_EOL;
// The ternary is an EXPRESSION: it yields one of two values.
$hasToken = true;
$route = $hasToken ? 'fast line' : 'slow line';
echo $route, PHP_EOL;
// ?? (null coalescing) yields the left side unless it is null or unset.
$override = null;
echo $override ?? 'green', PHP_EOL; // left is null, so 'green'
// ??= assigns only when the target is null or unset.
$override ??= 'amber';
echo $override, PHP_EOL; // now 'amber'
// ?? chains: the first defined, non-null value wins.
$next = null;
echo $next ?? $override ?? 'red', PHP_EOL; // 'amber'
// match is an EXPRESSION with strict (===) comparison and no fall-through.
$charter = 'charter';
$bay = match ($charter) {
'express' => 'bay 1',
'stopper' => 'bay 3',
default => 'siding 9',
};
echo "charter: {$bay}", PHP_EOL;
Output:
class express to platform 1
fast line
green
amber
amber
charter: siding 9
Read the two families against each other. if/elseif/else runs statements and is what you reach for when each branch does something -- writes a file, sends a response, throws. The ternary, ??, ??= and match are expressions: each one settles on a value, which is why they read so naturally on the right of an =. The mistake that stalls beginners is using an if to assign a variable in four branches when a single match would say the same thing in four lines with no repeated variable name and no chance of forgetting one branch.
Technical Depth: What The Condition Actually Compares
A conditional is only as trustworthy as the comparison inside it, and PHP has two comparison operators that look almost identical and behave very differently. == is loose: it will convert operands to a common type before comparing. === is strict: different types are never equal. The single most important habit in PHP conditionals is to reach for === by default and use == only when you have thought about the coercion and want it.
Loose Versus Strict, Under PHP 8 Rules
PHP 8 changed the most dangerous case. In PHP 7, comparing a number to a non-numeric string converted the number to a string only sometimes; the more common path converted the string to 0, so 0 == "freight" was true and a great many security checks failed open. PHP 8 fixed this: when one side is a number and the other a non-numeric string, the number is converted to a string and the two are compared as text. The table below is the PHP 8 behaviour, which is what you should assume everywhere.
| Comparison | Result | Why |
|---|---|---|
0 == "freight" | false | PHP 8 compares as strings; "0" is not "freight" |
0 === "freight" | false | different types are never strictly equal |
1 == "1" | true | the numeric string "1" is coerced to 1 |
1 === "1" | false | int and string are different types |
"" == 0 | false | PHP 8 no longer treats "" as 0 |
"" == false | true | the empty string is falsy, so both sides are false |
null == false | true | null is falsy and coerces to false |
null === false | false | null and false are distinct types |
<?php
declare(strict_types=1);
$checks = [
['0 == "freight"', 0 == "freight"],
['0 === "freight"', 0 === "freight"],
['1 == "1"', 1 == "1"],
['1 === "1"', 1 === "1"],
['"" == 0', "" == 0],
['"" == false', "" == false],
['null == false', null == false],
['null === false', null === false],
];
$width = 0;
foreach ($checks as [$label, $_]) {
$width = max($width, strlen($label));
}
foreach ($checks as [$label, $value]) {
printf("%-{$width}s : %s%s", $label, $value ? 'true' : 'false', PHP_EOL);
}
Output:
0 == "freight" : false
0 === "freight" : false
1 == "1" : true
1 === "1" : false
"" == 0 : false
"" == false : true
null == false : true
null === false : false
The line to stare at is the first one. Any code that wrote if ($status == 0) against a status that might arrive as a word was, in PHP 7, a latent open-the-gate bug. PHP 8 closes it, but the lesson stands: a comparison whose result depends on a coercion rule most people cannot recite is a comparison you cannot trust. if ($status === 0) says exactly what it means.
Match Interlocks Where A Chain Does Not
The match expression is the interlocking frame in code form. It compares with ===, it does not fall through, and if no arm matches and there is no default it throws UnhandledMatchError rather than silently doing nothing. That last property is the one worth paying for: a switch with a forgotten case does nothing and you find out in production; a match with a forgotten case throws the moment it meets an input you did not handle. Here it drives a junction that reads a train's tonnage against the limit for its class and either clears it or holds it.
<?php
declare(strict_types=1);
const PLATFORM = ['express' => 1, 'stopper' => 3, 'freight' => 5, 'empty' => 7];
const LIMIT = ['express' => 150, 'stopper' => 100, 'freight' => 400, 'empty' => 999];
$trains = [
['06:10', 'express', 120],
['06:35', 'stopper', 130],
['07:00', 'freight', 200],
['07:20', 'express', 180],
['07:45', 'empty', 0],
['08:15', 'freight', 450],
];
$fmt = "%-6s %-8s %4s %5s %4s %6s";
$rule = str_repeat('-', 38);
printf("{$fmt}%s", 'TIME', 'CLASS', 'TONS', 'LIMIT', 'PLAT', 'CLEAR', PHP_EOL);
echo $rule, PHP_EOL;
$cleared = 0;
$held = 0;
foreach ($trains as [$time, $class, $tons]) {
$limit = LIMIT[$class];
$plat = PLATFORM[$class];
$ok = $tons <= $limit;
$ok ? $cleared++ : $held++;
printf("{$fmt}%s", $time, $class, $tons, $limit, $plat, $ok ? 'yes' : 'HELD', PHP_EOL);
}
echo $rule, PHP_EOL;
echo "cleared {$cleared} held {$held} total ", count($trains), PHP_EOL;
Output:
TIME CLASS TONS LIMIT PLAT CLEAR
--------------------------------------
06:10 express 120 150 1 yes
06:35 stopper 130 100 3 HELD
07:00 freight 200 400 5 yes
07:20 express 180 150 1 HELD
07:45 empty 0 999 7 yes
08:15 freight 450 400 5 HELD
--------------------------------------
cleared 3 held 3 total 6
Three cleared, three held, and every hold is a train over the tonnage limit for its own class. Notice that the class name is looked up in two constant arrays, PLATFORM and LIMIT, keyed by the same string; if a train arrived with a class not in those arrays, LIMIT[$class] would raise a warning and yield null, and $tons <= null would compare against zero -- exactly the kind of unlisted-input hole a match with a default arm, or an explicit array_key_exists guard, is there to close.
Real World Example: The Post Office Counter Rate Calculator
The parcels counter at a post office is a decision engine wearing an apron. Every item that lands on the scale is priced by a cascade of conditionals: a base rate that depends on the item type, a surcharge that depends on the destination country, a fee if the customer wants it signed for, and a supplement if it is over the weight threshold for its type. The program below prices a tray of ten items the way the counter clerk would, one lookup and one comparison at a time, and totals the takings.
<?php
declare(strict_types=1);
const BASE = ['letter' => 85, 'packet' => 165, 'parcel' => 350]; // pence
const INTL_SURCHARGE = ['GB' => 0, 'DE' => 120, 'FR' => 120, 'US' => 250];
const HEAVY_AT = ['letter' => 0.10, 'packet' => 1.00, 'parcel' => 5.00]; // kg
const HEAVY_FEE = ['letter' => 20, 'packet' => 45, 'parcel' => 150];
const SIGN_FEE = 60;
$parcels = [
['P-001', 'letter', 0.08, 'GB', true],
['P-002', 'packet', 0.45, 'GB', false],
['P-003', 'packet', 1.20, 'DE', true],
['P-004', 'parcel', 4.80, 'FR', true],
['P-005', 'letter', 0.03, 'US', false],
['P-006', 'parcel', 12.50, 'GB', true],
['P-007', 'packet', 0.90, 'GB', true],
['P-008', 'letter', 0.05, 'DE', false],
['P-009', 'parcel', 6.00, 'US', false],
['P-010', 'packet', 0.30, 'FR', true],
];
$hfmt = "%-6s %-7s %5s %2s %1s %5s %5s %5s %5s %7s";
$rfmt = "%-6s %-7s %5.2f %2s %1d %5d %5d %5d %5d %7d";
$rule = str_repeat('-', 57);
printf("{$hfmt}%s", 'ID', 'TYPE', 'KG', 'TO', 'S', 'BASE', 'INTL',
'SIGN', 'OVER', 'TOTAL', PHP_EOL);
echo $rule, PHP_EOL;
$total = 0;
$intl = 0;
$heavy = 0;
$signed = 0;
foreach ($parcels as [$id, $type, $kg, $dest, $sg]) {
$base = BASE[$type];
$isurc = INTL_SURCHARGE[$dest];
$sfee = $sg ? SIGN_FEE : 0;
$over = $kg > HEAVY_AT[$type] ? HEAVY_FEE[$type] : 0;
$cost = $base + $isurc + $sfee + $over;
$total += $cost;
if ($isurc > 0) { $intl++; }
if ($over > 0) { $heavy++; }
if ($sg) { $signed++; }
printf("{$rfmt}%s", $id, $type, $kg, $dest, $sg, $base, $isurc,
$sfee, $over, $cost, PHP_EOL);
}
echo $rule, PHP_EOL;
printf("{$hfmt}%s", '', 'TOTAL', '', '', '', '', '', '', '', $total, PHP_EOL);
printf("international %d overweight %d signed %d of %d items%s",
$intl, $heavy, $signed, count($parcels), PHP_EOL);
Output:
ID TYPE KG TO S BASE INTL SIGN OVER TOTAL
---------------------------------------------------------
P-001 letter 0.08 GB 1 85 0 60 0 145
P-002 packet 0.45 GB 0 165 0 0 0 165
P-003 packet 1.20 DE 1 165 120 60 45 390
P-004 parcel 4.80 FR 1 350 120 60 0 530
P-005 letter 0.03 US 0 85 250 0 0 335
P-006 parcel 12.50 GB 1 350 0 60 150 560
P-007 packet 0.90 GB 1 165 0 60 0 225
P-008 letter 0.05 DE 0 85 120 0 0 205
P-009 parcel 6.00 US 0 350 250 0 150 750
P-010 packet 0.30 FR 1 165 120 60 0 345
---------------------------------------------------------
TOTAL 3650
international 6 overweight 3 signed 6 of 10 items
Every column on a row is the visible result of one conditional or one lookup, which is what makes the sheet auditable: P-003 is a 1.20 kg packet, over the 1.00 kg packet threshold, so it carries the 45 pence overweight fee; P-006 is a 12.50 kg parcel to a domestic address, so it pays the parcel base and the parcel heavy fee but nothing international. The three counters at the foot are incremented by three independent if statements, and because each guards a different fact -- a positive surcharge, a positive overweight fee, a true signed flag -- they cannot interfere with one another. Reading down the INTL column and counting the non-zero entries gives six, which is what the footer claims.
The design reads cleanly, but there is a real flaw hiding in the ternary $over = $kg > HEAVY_AT[$type] ? HEAVY_FEE[$type] : 0, and it is not a rough edge -- it is a correctness bug waiting for a new item type. The two heavy constants, HEAVY_AT and HEAVY_FEE, are separate arrays that must be kept in lockstep by hand. Add a 'large parcel' type to BASE and forget to add it to HEAVY_AT, and HEAVY_AT[$type] yields null, $kg > null is $kg > 0 which is true for every real item, so HEAVY_FEE[$type] is read -- also null, also a warning -- and the fee silently becomes zero while the counter still counts the item as not overweight. The whole cascade keeps running and produces a plausible, wrong price. The fix is to make the type a single source of truth: one enum or one array of structs per type carrying its base rate, threshold and fee together, so that a type either exists completely or does not exist at all, and match on it with no default so an unknown type throws instead of pricing itself at a discount.
Common Mistakes
- Using
==where you meant===. The loose operator invites a
coercion you did not think about. if ($count == "0") is true for the string "0", the integer 0 and the float 0.0; if ($count === 0) is true for exactly one of them. Default to strict, and reach for loose only with a comment saying which coercion you are relying on.
- Assigning inside a condition by writing
=for==.if ($x = 5)
assigns 5 to $x and then tests 5, which is always truthy. PHP will not stop you. Some codebases write the constant on the left -- if (5 == $x) -- so that a slipped = becomes a fatal "cannot assign to literal" instead of a silent bug; at minimum, turn on static analysis that flags assignment in a condition.
- Relying on
switchfall-through by accident. Aswitchcase without
a break falls into the next case and keeps executing. Sometimes that is deliberate, but far more often it is a forgotten break that runs two branches where one was meant. match has no fall-through at all, so prefer it whenever each arm is a single value or expression.
- Forgetting the
defaultarm. Anif/elseifwith no finalelse,
or a match with no default, has no plan for the input you did not foresee. The if chain silently does nothing; the match throws UnhandledMatchError. The throw is usually what you want -- an unhandled case is a bug -- but you must decide, not leave it to chance.
- Confusing
??with?:. The null coalescing??checks only for
null or unset and does not warn on an undefined variable; the short ternary ?: checks for any falsy value, so $qty ?: 10 replaces a legitimate 0 with 10. Use ?? for "might be missing" and ?: only when you truly want every falsy value treated the same.
- Deeply nesting conditionals instead of returning early. Four levels of
if indented inside each other hide the one path that matters. Invert the guards and return -- if (!$user) { return; } at the top -- so the happy path runs down the left margin unindented and each precondition is stated once.
- Chaining
elseifwhere ranges overlap. `if ($n > 10) ... elseif
($n > 5) ...` works only because the first hit wins and order was chosen carefully. Reorder those two rungs and every number above ten takes the wrong branch. When branches are ranges, make the boundaries explicit and test them, because the correctness lives entirely in the ordering.
- Treating
matcharms as loose likeswitch.matchuses===,
so match ($id) { "1" => ... } will not match the integer 1. This bites when a value arrives from a database or a form as a string and you wrote the arm as an integer, or vice versa. Normalise the type before the match, or write the arm in the type the value actually has.
- Putting side effects in a ternary.
$ok ? save() : log()runs one of
two functions for their effects and discards a value nobody wanted; it reads as data but behaves as control flow. Ternaries are for choosing a value. When the branches do something, write an if, so the reader sees control flow where control flow is happening.
Best Practices
- Default to
===and!==. Strict comparison removes an entire class of
coercion surprises, and on the rare occasion you want a coercion, a loose operator with a comment documents that you chose it on purpose.
- Reach for
matchwhen every branch produces a value from a single subject,
and keep if/elseif/else for branches that execute statements. Matching the tool to statement-versus-expression makes the intent legible at a glance.
- Give every decision a home for the unexpected input: an
else, a
default, or a deliberate throw. Decide whether an unhandled case is a valid "do nothing" or a bug, and encode that choice rather than leaving a gap.
- Return early to keep the nesting flat. Handle the error and boundary cases
at the top of the function with guard clauses, so the main logic is never buried under preconditions and each condition is checked exactly once.
- Use
??for values that might be null or absent and?:only when every
falsy value should collapse to the fallback. Being precise about which "emptiness" you mean prevents a real 0 or "" from being silently replaced.
- Keep the two sides of a comparison the same type. Normalise input to
int,
string or an enum at the boundary of your program, so that by the time a value reaches a match or an ===, its type is known and the comparison cannot be surprised.
- Extract a complicated condition into a named boolean or a small predicate
function. if ($isEligible) or if (canDispatch($order)) tells the reader why; a three-line boolean expression inline tells them only how.
- Prefer an
enumover a family of magic strings or integers as the subject
of a match. An enum makes the set of cases closed and known to the analyser, so a match over it can be proven exhaustive and an impossible case cannot be constructed in the first place.
Practice Exercises
- The strict audit. Take a function that uses
==in three places --
say, checking a status code, a user role string, and a nullable count -- and convert each to ===. For every one, write down in a comment what would have matched under == that no longer matches, and add an explicit cast or normalisation where the strict version would now reject a valid input.
- Match the junction. Write a
matchexpression that maps at least six
train classes to platform numbers, with a default that routes anything unlisted to a holding siding. Then remove the default and call it with an unlisted class; record the exact error, and explain in one sentence why the throwing version is safer than an if chain that silently falls through.
- Null coalescing versus short ternary. Build a settings loader that reads
five values from an array where some keys are missing, some are null, and one is the integer 0. Price the same lookups twice, once with ?? and once with ?:, and show a table of the two results side by side so the difference on the null key and the zero key is visible.
- Refactor the counter. Take the post office rate calculator from this
lesson and fix its flaw: replace the parallel BASE, HEAVY_AT and HEAVY_FEE arrays with a single source of truth per item type, and drive the pricing with a match that throws on an unknown type. Prove the fix by adding a new item type and confirming that a missing entry now fails loudly instead of pricing the item at zero.