Skip to content
Theory · Loops · lesson 1 of 6

while and do…while loops

What you'll learn

What you'll learn:

  • repeat code with while, do…while and for loops and count how many times the body runs;
  • skip an iteration with continue and leave a loop with break;
  • walk through a list of values with a foreach loop and explain why the loop variable is a copy;
  • spot an extra iteration and a forgotten counter step in nested loops.
A running track with a checkpoint arch $i <= 100, a runner under it and a lap counter marked $i++

To add up the numbers from 1 to 100, you would have to write a hundred terms in a row. Nobody does that: a repeated action is given to a loop, a construct that runs a block of code again and again.

Picture a running track. Before each lap, the runner passes a checkpoint arch, where they are told whether to keep running. After the lap, they make a mark on the lap counter. When the arch says "enough", the runner leaves the track.

A while loop works the same way: before each lap it checks a condition and, as long as the condition is true, runs its block. Here is the sum of the numbers from 1 to 100:

PHP
<?php

$total = 0;
$i = 1;
while ($i <= 100) {
    $total += $i;
    $i++;
}
echo $total, "\n"; // 5050
echo $i, "\n"; // 101

Let's walk through the program line by line:

  1. $total = 0; sets up the sum.
  2. $i = 1; is the lap counter: the runner starts with the first lap.
  3. while ($i <= 100) is the checkpoint arch: the condition in parentheses is checked before each lap.
  4. $total += $i; adds the lap number to the sum.
  5. $i++; makes the mark on the counter: $i grows by one.
  6. The first echo runs after the loop and prints 5050.

The condition comes before each iteration

The block in curly braces is called the loop body. One pass through the body is an iteration.

The key thing about while is the order of events:

  1. PHP checks the condition.
  2. If it is true, the body runs, and everything repeats from the first step.
  3. If the condition is false, the loop ends, and the program moves on.

That is why after the loop $i holds 101, not 100. The last iteration made $i equal to 101, the condition 101 <= 100 turned out false, and the loop ended. The second echo prints exactly that.

Interviewers like questions of this kind: how many times does the body run, and what does the counter hold after the loop? One rule always gives the answer: the condition is checked before the iteration.

Here the runner picture is inexact. A runner runs at least one lap, while while checks the condition even before the first iteration. If you start with $i = 200, the body never runs, and the sum stays 0.

Infinite loop

If the condition never becomes false, the loop never ends by itself. Such a loop is called infinite.

Most often it appears by accident: imagine that the line $i++ was left out of the first example. Then $i stays 1 forever, the condition 1 <= 100 is always true, and the runner circles lap after lap without a single mark.

PHP prints no message about it: the program keeps running quietly until someone stops it. In a terminal, the Ctrl+C key combination does that.

Sometimes an infinite loop is written on purpose, as while (true), and ended from the inside — for example, with return in a function. This function finds the first number whose square is greater than $limit:

PHP
function firstSquareOver($limit)
{
    $n = 1;
    while (true) {
        if ($n * $n > $limit) {
            return $n;
        }
        $n++;
    }
}

echo firstSquareOver(50), "\n"; // 8

Let's take the call firstSquareOver(50) apart:

  1. The search starts at $n = 1.
  2. For $n from 1 to 7, the square is not greater than 50, and the loop goes on.
  3. When $n is 8, the square is 64, and return gives back 8: the function ends, and the loop with it.

The do…while loop

while has a variant that runs the body first and checks the condition only afterwards: do…while. Its body runs at least once, like a real runner who checks the count after the lap.

PHP
$n = 10;
while ($n < 5) {
    echo 'while ', $n, "\n";
    $n++;
}
do {
    echo 'do ', $n, "\n"; // do 10
    $n++;
} while ($n < 5);

Let's see what happens here:

  1. The condition 10 < 5 is false from the start, so the body of while never runs.
  2. do runs the body without a check and prints do 10.
  3. Only then does while ($n < 5) check the condition: 11 < 5 is false, and the loop ends.

Note the semicolon after while ($n < 5). In do…while the condition comes last and closes the whole statement.

Use do…while when an action must run at least once and the repeat can be decided only afterwards: say, show a menu, then ask whether to show it again. Interviewers often ask how while differs from do…while: the first may never run its body, the second runs it at least once.

Common mistake

The semicolon after the condition of do…while is missing:

PHP
$n = 1;
do {
    echo $n, "\n";
    $n++;
} while ($n <= 3) // ✗
echo 'done', "\n";
TEXT
Parse error: syntax error, unexpected token "echo", expecting ";"

PHP expected ; after the condition and met the next echo instead. As you already know, a parse error stops the whole file from starting: not a single line runs, not even the ones above it. The fix is } while ($n <= 3);.

Key points

  • while checks the condition before each iteration and runs the body as long as the condition is true.
  • After the loop, the counter holds the value that made the condition false: 101, not 100.
  • A loop whose condition never becomes false is infinite; in a terminal, Ctrl+C stops it.
  • do…while runs the body first and checks the condition afterwards, and while (…) is followed by ;.