Loops: while, do-while, for and foreach

2.Loops: while, do-while, for and foreach

M

In this chapter

We'll learn how to repeat work with PHP's four loops — while, do-while, for and foreach — how to build a day's slots without writing the same line 18 times, the off-by-one mistake that adds a slot at closing time, a first look at arrays, nested loops, and how break and continue leave a loop or skip a round.

15–17 min

The Problem in Real Life

Mia's task: list Tom's slots for one day — 9:00, 9:30, 10:00, and so on, every 30 minutes, until the shop closes at 18:00. She stores times as minutes since midnight, the way she learned in Act 05: 9:00 is 540.

Her first try freezes the PHP Playground. After a few seconds it gives up. "You never changed the number," says Marcus, pointing at her loop. "It's still checking whether 540 is smaller than 1080. Forever."

Her second try runs. It prints 9:00, 9:30, 10:00 … and at the very end, 18:00.

M

The shop closes at 18:00. Why can a customer book 18:00?

Mia

Copy and Paste vs. a Loop

The same line, 18 times

Writing echo "9:00", echo "9:30" … by hand is long, and it breaks the day opening hours change.

A loop that never stops

If nothing inside the loop changes the condition, the loop runs until PHP gives up.

One round too many

<= instead of < adds a slot at exactly closing time — the classic off-by-one mistake.

Loops: while, do-while, for and foreach

What a loop is: a loop runs the same block of code again and again. Each run is called an iteration (or a round). Before or after each round, the loop checks whether to go again. PHP has four loops:

  • while: repeats as long as a condition is true; checks before each round.
  • do-while: like while, but checks after each round, so it always runs at least once.
  • for: a counting loop — the start, the condition and the step are written together in one line.
  • foreach: goes through every item in an array (a list of values), one by one.

while: while (condition) { ... } checks the condition; if it's true, it runs the block, then checks again, and so on. When the condition is false, PHP continues after the loop. Something inside the block must change the condition, or it will be true forever. That's an infinite loop, and it was Mia's first try: she forgot $minutes += 30. On a web server PHP stops a script after 30 seconds by default (the max_execution_time setting) with "Fatal error: Maximum execution time of 30 seconds exceeded". In the terminal there's no limit, so you stop it with Ctrl+C. To show a time like 9:00, the code uses sprintf("%d:%02d", ...): it fills a pattern with numbers, and %02d means "at least two digits, with a zero in front if needed". Act 07 explains sprintf() properly; for now, just copy it.

A while loop that lists slots
<?php
$minutes = 9 * 60; // 540 = 9:00
$closing = 11 * 60; // 660 = 11:00 (a short day, to keep the output small)
while ($minutes < $closing) {
echo sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), "\n";
$minutes += 30; // without this line, the loop never ends
}
// 9:00
// 9:30
// 10:00
// 10:30

The off-by-one mistake: Mia's second try used $minutes <= $closing. At 18:00, 1080 <= 1080 is true, so the loop ran one more round and added a slot that starts when the shop closes. Getting a loop's end wrong by exactly one round is so common it has a name: an off-by-one error. Ask yourself: is the end value included or not? A slot must start before closing time, so the condition is <. The code below shows both.

Mia's off-by-one error
<?php
$closing = 11 * 60; // 11:00
$minutes = 9 * 60;
while ($minutes <= $closing) { // <= includes closing time
$last = $minutes;
$minutes += 30;
}
echo "With <=, the last slot is ", sprintf("%d:%02d", intdiv($last, 60), $last % 60), "\n";
// With <=, the last slot is 11:00 — the shop is already closed
$minutes = 9 * 60;
while ($minutes < $closing) { // < stops before closing time
$last = $minutes;
$minutes += 30;
}
echo "With <, the last slot is ", sprintf("%d:%02d", intdiv($last, 60), $last % 60), "\n";
// With <, the last slot is 10:30

do-while: do { ... } while (condition); runs the block first and checks afterwards, so the block always runs at least once — even when the condition is false from the start. With a plain while, the block may run zero times. Use do-while when the first round must happen anyway, such as "make a booking code, and make a new one while it's already taken". It's the least used of the four loops. Don't forget the semicolon after while (...).

while may run zero times; do-while always runs once
<?php
$closing = 18 * 60;
$minutes = 18 * 60; // already closing time
while ($minutes < $closing) {
echo "while: $minutes\n"; // never runs
$minutes += 30;
}
do {
echo "do-while: $minutes\n"; // runs once, then checks
$minutes += 30;
} while ($minutes < $closing);
// do-while: 1080

for: most loops have the same three parts: a starting value, a condition, and a step. for puts all three in one line: for ($minutes = 540; $minutes < 1080; $minutes += 30) { ... }. PHP runs the first part once, then checks the condition before every round, and runs the third part after every round. It's the same loop as the while above, but you can see where it starts, when it stops and how it moves in one place. Use for whenever you count: numbers, minutes, steps of 30.

The same slots with a for loop
<?php
for ($minutes = 9 * 60; $minutes < 11 * 60; $minutes += 30) {
echo sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), "\n";
}
// 9:00
// 9:30
// 10:00
// 10:30

A first look at arrays, and foreach: an array holds many values in one variable. $slots = []; is an empty array, and $slots[] = "9:00"; adds a value to the end. You can also give each item a name, called a key: ["Haircut" => 25, "Beard trim" => 10]. count($slots) tells you how many items there are. Act 08 covers arrays in depth. foreach is the loop made for them: foreach ($slots as $slot) runs once for every item and puts the item in $slot. With keys, foreach ($prices as $service => $price) gives you both. There's no condition to get wrong: it stops when the items run out.

Arrays and foreach
<?php
$slots = []; // an empty array
$slots[] = "9:00"; // [] = "add to the end"
$slots[] = "9:30";
$slots[] = "10:00";
foreach ($slots as $slot) {
echo "Free: $slot\n";
}
echo count($slots), " slots\n";
$prices = ["Haircut" => 25, "Beard trim" => 10]; // each item has a key
foreach ($prices as $service => $price) {
echo "$service: £$price\n";
}
// Free: 9:00
// Free: 9:30
// Free: 10:00
// 3 slots
// Haircut: £25
// Beard trim: £10

Nested loops: a loop's block can contain another loop. The inner loop runs completely for every round of the outer one. For example, for every day of the week, list every slot of that day. Two days with two slots each gives four rounds of the inner block. Be careful with size: 7 days times 18 slots is 126 rounds, but 1,000 customers times 1,000 bookings is a million.

A loop inside a loop
<?php
$days = ["Monday", "Tuesday"];
foreach ($days as $day) {
echo "$day:";
for ($minutes = 9 * 60; $minutes < 10 * 60; $minutes += 30) {
echo " ", sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60);
}
echo "\n";
}
// Monday: 9:00 9:30
// Tuesday: 9:00 9:30

break and continue: sometimes you want to leave a loop early. break ends the loop at once, and PHP continues after it. Use it when you've found what you were looking for, like the first free slot. continue ends only the current round and jumps to the next one. Use it to skip items, like the slots in Tom's lunch break. In nested loops, both apply to the innermost loop. break 2 leaves two loops at once, and continue 2 jumps to the next round of the outer loop. One trap: inside a switch (chapter 3), continue acts like break, and PHP warns you to write continue 2 instead.

continue skips a round; break ends the loop
<?php
// continue: skip the lunch break (13:00 to 14:00), keep looping
for ($minutes = 12 * 60; $minutes < 15 * 60; $minutes += 30) {
if ($minutes >= 13 * 60 && $minutes < 14 * 60) {
continue;
}
echo sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), " ";
}
echo "\n";
// 12:00 12:30 14:00 14:30
// break: stop at the first free slot
$booked = [540, 570]; // 9:00 and 9:30 are taken
for ($minutes = 540; $minutes < 1080; $minutes += 30) {
if (!in_array($minutes, $booked, true)) { // "is it NOT in the list?"
echo "First free slot: ", sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), "\n";
break;
}
}
// First free slot: 10:00
break 2 leaves two loops at once
<?php
$booked = ["Monday" => [540, 570], "Tuesday" => [540]];
foreach (["Monday", "Tuesday"] as $day) {
for ($minutes = 540; $minutes < 600; $minutes += 30) {
if (!in_array($minutes, $booked[$day], true)) {
echo "First free: $day ", sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), "\n";
break 2; // leave the for AND the foreach
}
}
}
echo "Search finished.\n";
// First free: Tuesday 9:30
// Search finished.

Which loop to use: use foreach for the items of an array, for for counting, while when you can't know the number of rounds in advance, and do-while when the first round must always run. The table below sums them up.

Table — PHP's four loops
LoopChecks the conditionBest for
whileBefore each round, so it may run 0 timesRepeating until something changes, number of rounds unknown
do-whileAfter each round, so it runs at least onceDo it once, then repeat while needed
forBefore each round; start and step in the same lineCounting: numbers, minutes, steps of 30
foreachNo condition: once per itemGoing through every item of an array

Key Takeaway

A loop repeats a block. while checks before each round, do-while after (so it runs at least once), for puts start, condition and step in one line, and foreach visits every item of an array. Something must end every loop — or it runs until PHP gives up. Decide whether the end value is included (< or <=) to avoid off-by-one errors. break leaves a loop; continue skips to the next round.

Why This Matters

A booking system is full of lists: the slots of a day, the days of a week, a customer's bookings, the services and their prices. Every one of them is shown, totalled or searched with a loop — usually foreach or for.

And the two classic loop bugs — a loop that never ends and a loop that runs one round too many — both have simple checks: does something change the condition, and is the end value included or not?

Mia's list now ends at 17:30. She finds the same for loop in the old slot builder — and it's correct, with <. So the loop isn't why Sunday gets slots. The loop only runs if the day has a closing hour, and that comes from a function called closingHour(), which is built from a statement she hasn't met yet: switch. That's the next chapter.