Concept Flow - Do-while loop execution model
Start
Execute body
Check condition
Yes| No
Repeat
The do-while loop runs the code inside the loop first, then checks the condition. If true, it repeats; if false, it stops.
<?php $i = 1; do { echo $i . " "; $i++; } while ($i <= 3); ?>
| Step | Variable i | Condition ($i <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | 1 <= 3 is True | Print 1, increment i to 2 | 1 |
| 2 | 2 | 2 <= 3 is True | Print 2, increment i to 3 | 2 |
| 3 | 3 | 3 <= 3 is True | Print 3, increment i to 4 | 3 |
| 4 | 4 | 4 <= 3 is False | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | 1 | 2 | 3 | 4 | 4 |
do-while loop syntax in PHP:
do {
// code to run
} while (condition);
Runs loop body first, then checks condition.
Repeats if condition true, stops if false.
Always runs at least once.