CodeBlanks Logo Icon CodeBlanks

The do-while loop

PHP course · Beginner · Lesson 44/116

Learn the do-while loop that runs at least once and how it differs from while.

The do-while loop

A do-while loop runs the body first, then checks the condition. Because of this, the body always runs at least once. Its shape is do { ... } while (condition);.

For example, $n = 1; do { echo $n; $n++; } while ($n <= 3); prints 1, 2 and 3 in turn. Since the condition is checked at the end, the body is guaranteed to run once.

do-while versus while

The main difference between do-while and while is where the condition is checked. In while it is checked at the top, in do-while at the bottom.

Because of this, a while body may never run, but a do-while body always runs at least once. If you want to show a menu at least once, do-while fits well: do { echo $menu; } while ($continue);.

Exercise Print 1 to 3 with do-while

Use a do-while loop to print the numbers from 1 to 3, one per line. Start $n at 1, increase it by one each step, and use the condition $n <= 3.

Show example solution
Start with do { }, write echo $n . "\n" and $n++ in the body, then end with while ($n <= 3);.
Example solution:
<?php
$n = 1;
// Numbers 1 to 3
do {
    echo $n . "\n";
    $n++;
} while ($n <= 3);

Test yourself

  1. At least how many times does a do-while body run?

    • 1
    • 0
    • 2
    • Only if the condition is true
    Show answer

    1 — Correct. do-while runs the body first, then checks the condition.

  2. Complete the do-while

    $n = 3;
    do {
        echo $n;
        $n--;
    } ____ ($n >= 1);
    Show answer
    $n = 3;
    do {
        echo $n;
        $n--;
    } while ($n >= 1);
  3. Match each loop type to its trait

    for
    Fixed repeats with a counter
    while
    Condition checked first
    do-while
    Body runs at least once
  4. What is the output of the code below?

    $n = 5;
    do {
        echo $n;
        $n--;
    } while ($n > 5);
    • 43210
    • 5432
    • 5
    • Empty
    Show answer

    5 — Correct. The body runs once and prints 5; then the condition is false.

All lessons in Beginner