while, do-while and for
A while loop repeats while its condition stays true, do-while always runs at least once, and a for loop packs start, condition and step into one line for counted repetition.
Choose loop entry conditions and updates that make termination clear.
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.