← Back to PHP Course | Chapter 4: Control Flow | Lesson 11 of 14

PHP do-while Loop

Basic do-while Loop

A do-while loop is a post-test loop: it runs the loop body first, and only checks the condition *after* that first run has already completed — the opposite order from a regular while loop, which tests before ever entering the body.

Example: Basic do-while Loop

php
<?php
$i = 1;
do {
    echo $i . "\n";
    $i++;
} while ($i <= 3);
?>

Guaranteeing One Run

Because the condition check happens after the body runs, a do-while loop is guaranteed to execute at least once, even if the condition would have evaluated to false immediately — this is the one meaningful behavioral difference from a plain while loop.

Example: Guaranteeing One Run

php
<?php
$i = 10;
do {
    echo "This runs at least once, i=$i\n";
} while ($i < 5);
?>

Updating Variables inside Loop

The variable your condition checks has to change somewhere inside the loop body, or the condition will keep re-evaluating to the exact same result forever — an infinite loop that never terminates, since nothing inside the loop is moving it toward the stopping point.

Example: Updating Variables inside Loop

php
<?php
$i = 0;
do {
    echo $i . "\n";
    $i++; // must update, or this loop never ends
} while ($i < 3);
?>

Simulation of Menu Runs

A menu that should display its options at least once — even before the user has made any choice yet — is a natural fit for do-while: you want the 'show options' step to run first regardless, then keep repeating only if the user asks for another round.

Example: Simulation of Menu Runs

php
<?php
$choice = "exit";
do {
    echo "1. Start\n2. Settings\n3. Exit\n";
} while ($choice !== "exit");
?>

Nested do-while Loops

Nesting one do-while loop inside another lets an inner loop run its full guaranteed-at-least-once cycle for every single pass of the outer loop, which is useful for building grid-like or multi-dimensional repeated structures.

Example: Nested do-while Loops

php
<?php
$i = 1;
do {
    $j = 1;
    do {
        echo "$i,$j  ";
        $j++;
    } while ($j <= 2);
    echo "\n";
    $i++;
} while ($i <= 2);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.