
Wikis & learning
Make one pass before testing a condition
A do-while loop is useful when the first operation must happen even when no further work is expected. A regular while loop checks its condition before the first operation.
A do-while loop is useful when the first operation must happen even when no further work is expected. A regular while loop checks its condition before the first operation.
Walkthrough
This example counts down a short checklist and prints the value before decrementing. Trace the state at the top and the bottom of each pass to see why the final printed number is one.
PHP example
<?php
$checks = 2;
do {
echo 'Check ', $checks, PHP_EOL;
$checks--;
} while ($checks > 0);Expected output
Check 2
Check 1Change and check
Set the starting count to zero. The loop still prints once. Decide whether that behavior would fit a real task queue.
Discussion
Sign in to participate.



