Repeating work
Loops run the same block of code many times. Computers are good at repetition: printing every product, retrying a failed request, adding up a list of numbers. PHP has four loops. This lesson covers the two that repeat while a condition is true: while and do-while. The next one covers for and foreach, which you will use even more often.
while
A while loop checks a condition, runs its body if the condition is true, then checks again, and so on. It stops as soon as the condition is false:
<?php
$count = 1;
while ($count <= 5) {
echo "Pass $count\n";
$count++;
}
echo "Finished with count = $count\n";Pass 1
Pass 2
Pass 3
Pass 4
Pass 5
Finished with count = 6Three parts make this work: the variable is set before the loop, the condition tests it, and the body changes it ($count++). Leave out the change and the condition stays true for ever.
while is the natural choice when you do not know in advance how many passes you need, only when to stop. For example, how many years does it take for savings to double at 7% interest?
<?php
$balance = 10000;
$years = 0;
while ($balance < 20000) {
$balance *= 1.07;
$years++;
}
printf("Doubled after %d years: %.2f\n", $years, $balance);Doubled after 11 years: 21048.52If the condition is false from the start, the body never runs at all, which is often exactly right: an empty list needs no processing.
do-while
A do-while loop runs the body first and checks the condition afterwards, so the body always runs at least once. That fits "try, then decide whether to try again" situations, such as generating a random code until it is not already in use:
<?php
$used = ["AB12", "CD34"];
$candidates = ["AB12", "CD34", "EF56"]; // stands in for random codes
$attempt = 0;
do {
$code = $candidates[$attempt];
$attempt++;
echo "Trying $code\n";
} while (in_array($code, $used, true));
echo "Using $code after $attempt attempts\n";Trying AB12
Trying CD34
Trying EF56
Using EF56 after 3 attemptsIn real code $code would come from random_int() or bin2hex(random_bytes(2)); a fixed list is used here so the output is predictable. Note the semicolon after while (...): it is required in a do-while.
break: leave the loop
break ends the loop immediately, wherever it appears in the body. It is useful when you are searching and have found what you need:
<?php
$stockLevels = ["Keyboard" => 60, "Headphones" => 25, "Puzzle" => 0, "Mug" => 120];
$names = array_keys($stockLevels);
$i = 0;
while ($i < count($names)) {
$name = $names[$i];
if ($stockLevels[$name] === 0) {
echo "First sold-out product: $name\n";
break;
}
$i++;
}First sold-out product: Puzzlecontinue: skip to the next pass
continue skips the rest of the current pass and goes straight back to the condition. It keeps the body flat when some items should be ignored:
<?php
$n = 0;
while ($n < 10) {
$n++;
if ($n % 3 !== 0) {
continue;
}
echo "$n is a multiple of 3\n";
}3 is a multiple of 3
6 is a multiple of 3
9 is a multiple of 3Be careful where the counter is changed. Here $n++ comes before continue. If it came after, continue would skip it, $n would never grow, and the loop would never end.
Nested loops and break 2
Loops can contain loops. break and continue affect the innermost loop, unless you give them a number: break 2 leaves two levels at once.
<?php
$row = 1;
while ($row <= 3) {
$col = 1;
while ($col <= 3) {
if ($row * $col === 4) {
echo "Found 4 at row $row, column $col\n";
break 2;
}
$col++;
}
$row++;
}
echo "After the loops\n";Found 4 at row 2, column 2
After the loopsInfinite loops on purpose
while (true) loops for ever unless something inside breaks out. It is a legitimate pattern for "keep going until a condition in the middle of the body", such as reading a file until it ends, as long as there is a clear break.
If you start an infinite loop by mistake from the command line, press Ctrl+C to stop it. On a web server, PHP stops a script after the max_execution_time setting (30 seconds by default).
Common mistakes
- Forgetting to change the loop variable, so the condition never becomes false.
- Off-by-one errors:
<versus<=decides whether the last value is included. - Placing continue before the counter update in a while loop.
- Leaving out the semicolon after
while (...)in a do-while.
Exercise
A product has 23 units in stock and customers buy 4 at a time. Use a while loop to print the stock after each sale until fewer than 4 remain, then print how many sales happened and how many units are left.
Show one possible answer
<?php
$stock = 23;
$sales = 0;
while ($stock >= 4) {
$stock -= 4;
$sales++;
echo "Sale $sales: $stock left\n";
}
echo "$sales sales, $stock units left\n";Sale 1: 19 left
Sale 2: 15 left
Sale 3: 11 left
Sale 4: 7 left
Sale 5: 3 left
5 sales, 3 units leftKey points
- while checks its condition before each pass, so the body may run zero times.
- do-while checks after each pass, so the body always runs at least once.
- break leaves the loop immediately; continue skips to the next pass.
- Something inside the loop must eventually make the condition false, or the loop never ends.