Skip to the workspace
Pebellslearn by building
Loops and Includes  ›  Lesson

while, do-while and for

Loops 13 minA 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.

php / while, do-while and for

Explore each scene at your own pace.

01 · The rule

The rule

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 0

do ... 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 taken

for 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:

  • break leaves the loop immediately.
  • continue skips 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.