A do...while loop is like while, but it checks the condition after the block. So the block always runs at least once.
<?php
$number = 10;
do {
echo "Number is $number\n";
$number++;
} while ($number <= 3);
Number is 10
The condition 10 <= 3 is false, but the block already ran once.
Compare it with while, which would print nothing here.
Notice the semicolon
A do...while ends with a semicolon after the condition. Forgetting it is a syntax error.
When to use it
Use do...while when the work must happen once before you can decide whether to repeat. Typical examples are “ask, then check the answer”, “try, then check if it worked” and menus.
<?php
$attempts = 0;
do {
$attempts++;
$success = $attempts >= 3; // pretend the third try works
echo "Attempt $attempts: " . ($success ? "ok" : "failed") . "\n";
} while (!$success && $attempts < 5);
Attempt 1: failed
Attempt 2: failed
Attempt 3: ok
Generate a unique code
<?php
$taken = ["A1", "A2"];
$candidates = ["A1", "A2", "A3"];
$i = 0;
do {
$code = $candidates[$i++];
} while (in_array($code, $taken, true));
echo "Free code: $code";
Free code: A3
do…while is rare
for or foreach. Keep do...while for the cases where “run first, check later” is exactly what you mean.