The Analogy: The Bottling Line At The Dairy
Walk into the bottling hall of a dairy and the first thing you notice is that nobody is filling bottles by hand. A stainless conveyor carries empty bottles past a filling head, a capping head, and a labelling head, and each bottle receives exactly the same three operations in exactly the same order. The line does not care whether there are forty bottles today or four thousand; it performs one cycle per bottle and stops when the last bottle has passed. That is a loop: a body of work written once, applied to each item in a stream, with the machinery -- not the operator -- keeping count of where it is.
The line has two ways of knowing when to stop, and they map exactly onto the loop constructs. Some machines run for a counted number of cycles: the palletiser stacks bottles until it has forty on the pallet, then wraps it -- that is a for loop, driven by a counter that starts, tests, and increments. Other machines run until a condition changes: the filler runs while the supply tank is above its low mark and stops when a float switch trips -- that is a while loop, driven by a test that is checked before each cycle. And the most common case of all is "do this to every bottle in the crate", where the crate itself knows how many bottles it holds and hands them out one at a time; that is foreach, and in PHP it is the workhorse you will reach for far more often than the other two.
A good line also has ways to handle the individual item that is not quite normal without shutting down. If a bottle comes past chipped, a sensor kicks it into a reject chute and the line carries straight on to the next bottle -- it does not stop, it just skips the rest of the work for that one item. That is continue. If something genuinely dangerous happens -- a bottle shatters inside the capping head -- the line hits an emergency stop and the whole run halts immediately, even though there are bottles still waiting. That is break. A line with neither of these is brittle: one bad bottle either jams the machine or, worse, gets filled and capped anyway and ships as a fault.
The failure that haunts a bottling line is the one where the machine never stops. If the float switch sticks closed, the filler keeps running after the tank is empty, drawing air, and the line runs forever producing nothing. In code this is the infinite loop: a while whose condition never becomes false because the body forgot to advance the thing the condition tests, or a for whose counter is modified inside the body so it never reaches its limit. The sister failure is the off-by-one: the palletiser told to stack "up to and including" forty when the pallet holds only forty from zero, reaching for a bottle that is not there. Every loop you write is a small promise that it will advance toward its end and stop exactly once, at the right place, and most loop bugs are a broken version of that promise.
Syntax or Core Structure
PHP has four looping constructs, and they divide cleanly by how they decide to keep going. for counts. while tests before each pass. do/while tests after, so the body always runs at least once. foreach walks the elements of an array or iterable and is the one you will use most.
<?php
declare(strict_types=1);
// while: test first, so a false condition means zero passes
$n = 3;
$countdown = '';
while ($n > 0) {
$countdown .= $n;
$n--;
}
echo $countdown, PHP_EOL; // 321
// do-while: body runs once before the test is ever seen
$m = 0;
do {
echo 'run once';
} while ($m > 0);
echo PHP_EOL;
// for: initialise, test, advance -- all three in the header
$digits = '';
for ($i = 1; $i <= 3; $i++) {
$digits .= $i;
}
echo $digits, PHP_EOL; // 123
// foreach: walk key => value; PHP preserves insertion order
$crate = ['top' => 500, 'mid' => 502, 'low' => 498];
$parts = [];
foreach ($crate as $slot => $ml) {
$parts[] = "{$slot}={$ml}";
}
echo implode(', ', $parts), PHP_EOL; // top=500, mid=502, low=498
Output:
321
run once
123
top=500, mid=502, low=498
Two details in that output are worth pausing on. The do/while printed run once even though its condition $m > 0 was false from the start: the body of a do/while always runs before the test, which is exactly what you want for "prompt, then validate, then maybe prompt again" and exactly what you do not want if the body assumes the condition already holds. And the foreach printed the slots in the order they were inserted -- top, mid, low -- because a PHP array is an ordered map, not a hash bag; the loop visits keys in insertion order every time, which is why building a display string with foreach is deterministic.
Technical Depth: The Reference Trap And Loop Control
Two features of PHP loops cause more real bugs than all the others combined: the by-reference foreach, which can quietly corrupt the array you just finished walking, and the multi-level break/continue, which is powerful and easy to get the wrong number on. Both reward understanding exactly what the loop variable is on each pass.
Which Loop To Reach For
| Construct | Runs the body | Best for |
|---|---|---|
for | a counted number of times | a known count, or index arithmetic you need |
while | while a condition holds, tested first | draining a queue, reading until end-of-input |
do/while | same, tested after, so at least once | prompt-then-validate, retry-at-least-once |
foreach | once per element of an array/iterable | the default: doing a thing to every item |
The rule of thumb is to prefer foreach unless you genuinely need an index or a condition that is not "for every element". A for ($i = 0; $i < count($a); $i++) over an array is almost always a foreach in disguise, and the foreach version cannot run off the end or skip an element.
foreach By Reference Corrupts The Last Element
Writing foreach ($array as &$item) binds $item as a reference to each element so you can modify the array in place. The trap is that after the loop ends, $item is still a live reference to the last element. If you then use that same variable name in a second foreach, every assignment to it writes through to the last element of the original array. The fix is a single unset($item) after the by-reference loop.
<?php
declare(strict_types=1);
// the trap: a by-reference loop, then a second foreach reusing $r
$bad = [500, 502, 498];
foreach ($bad as &$r) { // legitimately bump each reading by one
$r += 1;
}
// $bad is now 501, 503, 499 -- but $r still aliases $bad[2].
foreach ($bad as $r) {
// each pass assigns to $r, which still writes through to $bad[2]
}
echo 'no unset : ', implode(', ', $bad), PHP_EOL; // 501, 503, 503
// the fix: unset the reference the moment the by-reference loop ends
$good = [500, 502, 498];
foreach ($good as &$r) {
$r += 1;
}
unset($r); // sever the reference before reusing the name
foreach ($good as $r) {
// now $r is an ordinary copy; the array is untouched
}
echo 'unset ok : ', implode(', ', $good), PHP_EOL; // 501, 503, 499
Output:
no unset : 501, 503, 503
unset ok : 501, 503, 499
The middle line is the bug in the wild: the last element became 503 instead of 499, silently, with no error, because the second loop's variable was still wired to $bad[2]. It corrupts only the last element, so a quick glance at the front of the array shows nothing wrong -- which is exactly why this bug survives code review. Make it a reflex: every foreach (... as &$x) is immediately followed by unset($x) when the loop ends, or better, is factored into a small function so the reference cannot outlive its scope.
break And continue Take A Level
Plain continue skips the rest of the current pass; plain break leaves the loop. Inside nested loops you can give either one a number: break 2 leaves two levels of loop at once, continue 2 skips to the next pass of the loop two levels out. This is how you stop an entire nested scan the instant you find what you were looking for.
<?php
declare(strict_types=1);
$crates = [
['C1', [500, 501, 499]],
['C2', [500, 540, 500]], // 540 is the hard fault
['C3', [500, 500, 500]],
];
$hardLimit = 520;
$found = '';
$scanned = 0;
foreach ($crates as [$id, $bottles]) {
foreach ($bottles as $ml) {
$scanned++;
if ($ml === 500) {
continue; // nominal bottles are uninteresting
}
if ($ml > $hardLimit) {
$found = "{$id} at {$ml}ml";
break 2; // leave BOTH loops at once
}
}
}
echo "scanned {$scanned} bottles before the hard fault", PHP_EOL;
echo "hard fault: {$found}", PHP_EOL;
Output:
scanned 5 bottles before the hard fault
hard fault: C2 at 540ml
The scan touched all three bottles of C1 and the first two of C2 -- five in total -- then break 2 abandoned both loops the moment the 540 ml bottle was found, so C2's third bottle and all of C3 were never examined. Had that been a plain break, it would have left only the inner loop and the outer loop would have carried on into C3, scanning bottles the code had already decided it did not need. The number after break is how many crates-deep the emergency stop reaches.
Real World Example: The End-Of-Shift Line Report
At the end of a shift the bottling line prints a report: for each crate, how many bottles were filled, how many came out under or over the fill tolerance, how many slots held a pulled sample rather than a bottle, and whether the crate should be quarantined. It is a nested loop -- crates on the outside, bottles on the inside -- with a continue to skip sample slots and running totals that have to reconcile at the foot. Nominal fill is 500 ml with a tolerance band of 492 to 508 ml, and a crate with two or more rejects is held back.
<?php
declare(strict_types=1);
const LOW = 492;
const HIGH = 508;
$crates = [
['C1', [500, 501, 499, 500, 498, 502]],
['C2', [500, 490, 500, 511, 500, 499]],
['C3', [495, 505, 500, 0, 500, 501]], // 0 = sample pulled, skip
['C4', [488, 489, 500, 500, 500, 500]],
['C5', [509, 500, 500, 500, 500, 500]],
];
$fmt = "%-5s %4s %3s %4s %5s %3s %6s";
$rule = str_repeat('-', 36);
printf("{$fmt}%s", 'CRATE', 'DONE', 'LOW', 'HIGH', 'EMPTY', 'REJ', 'STATE', PHP_EOL);
echo $rule, PHP_EOL;
$tDone = 0;
$tLow = 0;
$tHigh = 0;
$tEmpty = 0;
$tRej = 0;
$quar = 0;
foreach ($crates as [$id, $bottles]) {
$done = 0;
$low = 0;
$high = 0;
$empty = 0;
foreach ($bottles as $ml) {
if ($ml === 0) {
$empty++;
continue; // a pulled sample is not an inspected bottle
}
$done++;
if ($ml < LOW) {
$low++;
} elseif ($ml > HIGH) {
$high++;
}
}
$rej = $low + $high;
$state = $rej >= 2 ? 'QUAR' : 'pass';
if ($state === 'QUAR') {
$quar++;
}
$tDone += $done;
$tLow += $low;
$tHigh += $high;
$tEmpty += $empty;
$tRej += $rej;
printf("{$fmt}%s", $id, $done, $low, $high, $empty, $rej, $state, PHP_EOL);
}
echo $rule, PHP_EOL;
printf("%-5s %4d %3d %4d %5d %3d%s", 'TOTAL', $tDone, $tLow, $tHigh, $tEmpty, $tRej, PHP_EOL);
$slots = $tDone + $tEmpty;
printf("quarantined %d of %d crates slots %d = done %d + empty %d%s",
$quar, count($crates), $slots, $tDone, $tEmpty, PHP_EOL);
Output:
CRATE DONE LOW HIGH EMPTY REJ STATE
------------------------------------
C1 6 0 0 0 0 pass
C2 6 1 1 0 2 QUAR
C3 5 0 0 1 0 pass
C4 6 2 0 0 2 QUAR
C5 6 0 1 0 1 pass
------------------------------------
TOTAL 29 3 2 1 5
quarantined 2 of 5 crates slots 30 = done 29 + empty 1
The report reconciles, and that reconciliation is the point. Five crates of six slots each is thirty slots; the footer confirms 30 = done 29 + empty 1, so every slot was accounted for as either an inspected bottle or a pulled sample and none was silently dropped. C3 shows the continue at work: its fourth slot held a sample, so DONE is 5 rather than 6 and EMPTY is 1, and the sample was never tested against the tolerance band. C2 and C4 each carry two rejects and are marked QUAR; C5's single high reading is not enough to quarantine it, which is why the threshold is a comparison and not a mere "any reject" flag.
The design is sound but it has a genuine flaw, and it is one of loop hygiene rather than arithmetic. The five accumulator variables -- $tDone, $tLow, $tHigh, $tEmpty, $tRej -- are declared once outside the outer loop and mutated on every pass, and there is nothing structural stopping a later edit from reading or resetting one of them in the wrong place. The moment someone adds a second pass over $crates lower down and reuses $done or $rej as a scratch variable, the totals silently double-count or reset. The robust version computes each crate's figures in a small function that returns a struct, then sums those structs with array_reduce, so the running totals have no mutable existence outside the reduction and cannot be corrupted by a distant edit. Manual accumulators in a long loop body are the procedural cousin of the by-reference foreach trap: both work perfectly until a second piece of code touches the same name.
Common Mistakes
- The by-reference
foreachwith nounset.foreach ($a as &$v)
leaves $v bound to the last element after the loop, and the next foreach reusing $v corrupts $a's last element. Always unset($v) when a by-reference loop ends, or avoid the reference entirely and build a new array.
- Forgetting to advance the condition in a
while. `while ($row =
next()) is fine, but while ($i < $n) { doWork(); } with no $i++ inside runs forever. Every while needs the body to move the thing the condition tests, or an unconditional break` on some inner event.
- Off-by-one in a
for.for ($i = 0; $i <= count($a); $i++)walks one
past the end because indexes run 0 to count - 1. Use < for zero-based counts, and prefer foreach so the bound is never yours to get wrong in the first place.
- Calling
count()in the loop condition. `for ($i = 0; $i <
count($a); $i++) recomputes the length on every pass. Hoist it into a variable before the loop, or use foreach`, which walks the array without ever asking its length.
- Modifying an array while
foreachwalks it by value. Adding or
removing elements of the array inside a by-value foreach operates on the loop's internal copy, so your changes appear not to take effect and the loop visits the original elements. Collect the changes and apply them after, or loop over a snapshot with foreach (array_keys($a) as $k).
- Using
break/continuewith the wrong level.breakleaves one
loop; break 2 leaves two. Writing plain break where you meant break 2 leaves the inner loop but lets the outer loop carry on, so the scan continues past the point you thought you had stopped it. Count the loop levels deliberately.
- Confusing
continuewithbreak.continueskips the rest of this
pass and goes to the next item; break abandons the loop. Swapping them either processes items you meant to skip or stops a scan that should have gone on. Say out loud "skip this one" versus "stop entirely" before you type it.
- Building output with a trailing separator. `foreach ($a as $x) { echo
"$x, "; } leaves a stray , at the end. Collect the pieces into an array and implode(', ', $parts)`, which puts separators only between elements and never produces a trailing one.
- Reaching for a manual index loop when an array function fits. Summing,
filtering, or transforming an array with a hand-written for and an accumulator is more code and more chances to slip than array_sum, array_filter or array_map. Use the built-in when the whole loop body is one of those three shapes.
Best Practices
- Default to
foreachfor "do a thing to every element", and reservefor
for genuine index arithmetic and while for draining a source of unknown length. The construct should announce why the loop exists.
- Follow every
foreach (... as &$item)withunset($item)the instant the
loop closes, or factor the reference into its own function so it cannot leak into a later loop. Treat a lone by-reference loop as a smell.
- Hoist loop-invariant work out of the body. Anything that does not change
per pass -- a count(), a compiled pattern, a constant lookup -- is computed once before the loop, not recomputed on every iteration.
- Keep loop bodies short and single-purpose. If the body is doing three
different jobs, it is three loops or three function calls wearing one loop's clothing, and splitting them makes each one testable.
- Prefer the array functions --
array_map,array_filter,
array_reduce, array_sum -- when the loop's whole job is transform, select, or fold. They state intent and remove the accumulator you would otherwise have to manage by hand.
- Give a nested loop's
breakandcontinuean explicit level and a
comment when it is anything other than the innermost. break 2 // leave both loops costs nothing and stops the next reader from miscounting.
- Avoid mutating the array you are iterating over by value. Build a new array,
or iterate a snapshot of the keys, so the collection you are reading and the collection you are writing are never the same one mid-loop.
- Guarantee progress and termination. Before you leave a
whileor a
hand-rolled for, be able to point at the line that moves it toward its end, and convince yourself it runs on every path through the body.
Practice Exercises
- Four ways to count. Write the same task -- summing the integers 1 to
100 -- four times: with a for, a while, a do/while, and array_sum(range(1, 100)). Confirm all four print 5050, then write one sentence on which you would ship and why.
- Reproduce the reference trap. Build a three-element array, bump each
element with a by-reference foreach, then -- without unset -- run a second by-value foreach over a copy and print the result. Show the corrupted last element, then add the unset and show it fixed, so you have seen the bug make and unmake itself.
- Stop the scan early. Given a list of crates each holding a list of
readings, write a nested loop that finds the first reading above a hard limit and reports which crate it was in, using break 2 to stop immediately. Print how many readings were examined, and confirm it is fewer than the total.
- Reconcile a report. Extend the end-of-shift report to add a sixth crate,
then prove the footer still balances: the total slots must equal done plus empty. Then refactor the running totals into an array_reduce over per-crate structs and confirm the report is byte-for-byte identical to the loop version.