The do...while loop is a variation of the while loop. The key difference is that it checks the condition after executing the code block. This means the loop will always execute the block of code at least once.
The code is executed first, and only then is the condition tested. If the condition is true, the loop repeats.
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Even if the condition is false from the start, the do block will run exactly once. This is what separates it from a standard while loop.
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
// Outputs: The number is: 6
?>
do...while loop is the ideal choice.
| Loop Type | Condition Check | Minimum Iterations |
|---|---|---|
| while | Pre-condition (at the top) | 0 |
| do...while | Post-condition (at the bottom) | 1 |
;) after the while ($condition) part in a do-while loop. It is required for the code to compile correctly.