Do… while
The do…while loop is almost the same thing as the while loop, with one important twist:
it always runs the code at least once, even if the condition is already false.
PHP runs the block first → then checks the condition → if the condition is still true, it loops again.
This is useful when you need to “try something first, then decide whether to continue.”
A classic WordPress-ish example would be trying to load a remote request at least once, retrying only if the first attempt fails.
Structure:
do {
// run this at least once
} while ($condition);
Example from W3:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
This prints 1–5.
But if $i = 8:
$i = 8;
do {
echo $i; // prints 8 anyway
$i++;
} while ($i < 6);
The loop stops immediately after the first run, because the condition fails.
You can use break to stop early:
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
And continue to skip a specific iteration:
$i = 0;
do {
$i++;
if ($i == 3) continue;
echo $i;
} while ($i < 6);
That’s the whole idea:
do…while gives you one guaranteed run, then behaves like a normal loop.