PHP Do While Loop
A do...while loop runs its body once before it checks the condition, guaranteeing at least one pass even when the condition is false to begin with.
The key difference
The do...while loop is a close cousin of the while loop, but it flips the order of events. It runs the body first and tests the condition afterwards. Because of this, the body always executes at least one time, no matter what the condition says. A regular while loop, by contrast, can skip its body entirely if the condition is false from the outset.
Basic do...while
<?php
$count = 1;
do {
echo "Count is $count\n";
$count++;
} while ($count <= 5);
?>Runs at least once
The example below shows the behaviour that makes do...while special. Even though the starting value already fails the condition, the body still runs a single time before PHP checks the test and exits. Compare this to a while loop with the same condition, which would print nothing at all.
The body runs even when the test is false
<?php
$attempts = 10;
do {
echo "This message prints once.\n";
$attempts++;
} while ($attempts < 5);
?>- Use do...while when the work must happen before you can judge whether to repeat it.
- Good examples include prompting a user until valid input is given, or processing a menu choice.
- Always change the control variable inside the body to avoid an endless loop.
- The break and continue statements work here just as they do in other loops.
In practice, do...while is the least used of the four PHP loops, but it is the perfect tool whenever your logic follows the pattern 'do the thing, then decide if you should do it again'.