PHP do-while Loop
In this page:
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
$i = 1;
do {
echo $i . "\n";
$i++;
} while ($i <= 3);
?>
Login to try C/C++/Java/PHP code in the editor
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
$i = 10;
do {
echo "This runs at least once, i=$i\n";
} while ($i < 5);
?>
Login to try C/C++/Java/PHP code in the editor
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
$i = 0;
do {
echo $i . "\n";
$i++; // must update, or this loop never ends
} while ($i < 3);
?>
Login to try C/C++/Java/PHP code in the editor
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
$choice = "exit";
do {
echo "1. Start\n2. Settings\n3. Exit\n";
} while ($choice !== "exit");
?>
Login to try C/C++/Java/PHP code in the editor
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
$i = 1;
do {
$j = 1;
do {
echo "$i,$j ";
$j++;
} while ($j <= 2);
echo "\n";
$i++;
} while ($i <= 2);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: