PHP While Loops
Loops repeat a block of code. PHP has four loop statements: while, do...while, for and foreach. This lesson covers the two "condition" loops, which keep going as long as a condition stays true. They are the right choice when you don't know in advance how many repetitions you need.
| Loop | Checks the condition | Runs at least once? |
|---|---|---|
while |
before each pass | no |
do...while |
after each pass | yes |
for |
before each pass (counter built in) | no |
foreach |
— (walks through an array) | no, for an empty array |
The while loop
while (condition) {
// repeated while condition is true
}PHP evaluates the condition; if it is truthy, the body runs, then the condition is checked again. As soon as it becomes false, the program continues after the loop.
<?php
$countdown = 5;
while ($countdown > 0) {
echo $countdown, "... ";
$countdown--;
}
echo "Liftoff!\n";5... 4... 3... 2... 1... Liftoff!
Something inside the body must eventually make the condition false — here $countdown--. If you forget it, the loop runs forever.
Note: If you accidentally write an infinite loop in a playground, it is stopped automatically after a time limit.
Loops with an unknown number of steps
while shines when the number of iterations depends on the data. How many years does it take for savings to double at 6% interest?
<?php
$balance = 1000.0;
$rate = 0.06;
$years = 0;
while ($balance < 2000) {
$balance *= 1 + $rate;
$years++;
}
printf("After %d years the balance is %.2f\n", $years, $balance);After 12 years the balance is 2012.20
Another classic: the Collatz sequence. Halve even numbers, turn odd numbers into 3n + 1, and stop at 1.
<?php
$n = 6;
$steps = [$n];
while ($n !== 1) {
$n = $n % 2 === 0 ? intdiv($n, 2) : 3 * $n + 1;
$steps[] = $n;
}
echo implode(" -> ", $steps), "\n";
echo "Steps: ", count($steps) - 1, "\n";6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Steps: 8
The do...while loop
A do...while loop runs its body first and checks the condition afterwards. That guarantees at least one pass, even when the condition is false from the start. Note the semicolon after the closing while (...).
<?php
$n = 10;
do {
echo "do...while ran with n = $n\n";
$n++;
} while ($n < 5);
$m = 10;
while ($m < 5) {
echo "while ran with m = $m\n";
$m++;
}
echo "Done\n";do...while ran with n = 10
Done
The while loop never ran because 10 < 5 is false before the first pass, but the do...while body executed once.
A typical real use is "try, then check": generate something, and repeat only if the result isn't acceptable — for example, retrying an operation or re-asking for input until it is valid. Here we keep dividing a number by 10 to count its digits; even 0 has one digit, so the body must run at least once:
$digits = 0;
do {
$digits++;
$number = intdiv($number, 10);
} while ($number > 0);Alternative syntax
Like if, while has a colon form that reads nicely in templates:
<?php while ($row = next_row()): ?>
<li><?= htmlspecialchars($row) ?></li>
<?php endwhile; ?>Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Never changing the loop variable | infinite loop | update it inside the body |
Off-by-one (<= vs <) |
one pass too many or too few | trace the first and last pass by hand |
Missing ; after do {...} while (...) |
parse error | end the statement with ; |
Using = instead of ==/=== in the condition |
assignment, often infinite | compare with === |
Tip: If you know exactly how many times to repeat (for example "10 times" or "once per array element"), a
fororforeachloop is clearer. Keepwhilefor "until something happens".
Test yourself
How many times does the body of do { ... } while (false); run?
- 0
- 1
- Forever
- It doesn't compile
What prints: $i = 3; while ($i > 0) { echo $i; $i -= 1; }?
321321012332
Which loop is the best fit for 'keep doubling until the value exceeds 1000'?
foreachwhileswitchmatch