while, do-while and for
Pageturn runs a flash sale: sell copies of Dune until stock runs out. On another page it prints page links 1 to 10. Both jobs repeat an action, but one repeats "until something happens" and the other repeats "a known number of times". PHP has a loop for each.
The rule
while repeats until a condition fails; for repeats a counted number of times.
while checks its condition before each round. If the condition is false from the start, the body never runs:
<?php
$stock = 3;
while ($stock > 0) {
echo "Selling one of $stock\n";
$stock--; // move towards the end!
}
// runs 3 times, then $stock is 0do ... while checks after each round, so the body always runs at least once. That suits "ask, then check the answer" situations:
do {
$code = generateCode(); // make a discount code
} while (codeExists($code)); // try again if it is takenfor packs the three parts of a counted loop into one line: start, condition, step.
for ($page = 1; $page <= 10; $page++) {
echo "<a href=\"?page=$page\">$page</a> ";
}It runs the start once, checks the condition before every round, and runs the step after every round.
Two keywords steer any loop:
breakleaves the loop immediately.continueskips the rest of this round and moves on to the next one.
The danger with while is the infinite loop: if nothing inside the body moves the condition towards false, the loop never ends. Forget $stock-- above and the sale never finishes.
The shortcut
Ask "do I know how many rounds before I start?" Yes → for. No, it depends on something that changes → while. Must run at least once → do ... while. Then check one thing: what in the body moves the loop towards stopping?
The loop
for ($i = 0; $i < 3; $i++) { echo $i; }
The classic off-by-one: $i <= 3 would give four rounds. Starting at 0 and using < gives exactly the count.
Drills
Answer fast — trust the rule.
How many times does the body run in $n = 0; while ($n > 0) { $n--; }?
Which loop always runs its body at least once?
What does for ($i = 1; $i <= 3; $i++) { echo $i; } print?
Inside a loop over 1 to 5, the body is if ($x === 2) continue; if ($x === 4) break; echo $x;. What is printed?
Remember
- while repeats until a condition fails; for repeats a counted number of times.
- Shortcut: known count → for; unknown → while; at least once → do-while.
- Trap: something in the body must move the loop towards stopping, and watch
<versus<=.
