The PHP do...while Loop
A do...while loop always runs its code at least one time. After that first run, it checks the condition and goes round again for as long as the condition stays true.
Note: The reason for this behavior is that the test sits at the bottom of the loop, after the code. Even a condition that is false from the start cannot stop the first run.
Do while loop basics
$i starts at 1, and the loop prints it and adds 1 until $i is no longer below 6:
Output: PHP script
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
Do while with false condition
Here $i starts at 8, which already fails the test $i < 6. The value still gets printed once, since PHP only looks at the condition after the code block has run:
Output: PHP script
<?php
$i = 8;
do {
echo $i;
$i++;
} while ($i < 6);
?>
Do while syntax
The general form looks like this, with the condition written after the closing brace:
do {
// code to be executed
} while (condition);
The PHP break Statement
The break statement ends a do...while loop early, whether or not its condition is still true.
Stop the loop with break
Printing stops when $i reaches 3, so only 1 and 2 appear:
Output: PHP script
<?php
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
?>
The PHP continue Statement
To leave out a single pass, use continue. The rest of that iteration is dropped, and the loop carries on with the following one.
Skip iteration with continue
Notice that $i is increased at the top of the body, before the check. When it equals 3 the echo is skipped, so 3 is missing from the output:
Output: PHP script
<?php
$i = 0;
do {
$i++;
if ($i == 3) continue;
echo $i;
} while ($i < 6);
?>