Loops

Introduction

Computers are good at doing the same job again and again without getting tired. A loop repeats a block of code. You use loops to print a list, add up numbers, search for a value, read every line of input or draw a pattern. PHP has four loops: for, while, do-while and foreach. Each one fits a different situation, and choosing the right one makes your code short and clear.

How it works

The for loop is the best choice when you know how many times to repeat. It has three parts in the brackets: a start, a condition and a step.

for ($i = 1; $i <= 5; $i++) {
    echo $i, " ";
}

PHP sets $i to 1, checks the condition, runs the block, then adds 1 and checks again. The loop ends when the condition becomes false.

The while loop checks a condition before every round, and it is best when you do not know the number of rounds in advance, for example "repeat until the input ends". The do-while loop checks the condition after the block, so it always runs at least once. Be careful with while: if nothing in the block changes the condition, the loop never ends. In this compiler a program that runs for more than ten seconds is stopped.

The foreach loop goes through an array. You can take only the values, or the key and the value:

foreach ([10, 20, 30] as $index => $value) { }

It is the clearest way to visit every item, because you cannot make an index mistake.

Two keywords change the flow. break leaves the loop at once. continue skips the rest of the current round and goes to the next one. Loops can also be put inside each other. The inner loop runs completely for every round of the outer loop, which is how you draw tables and patterns. For example, a pattern of stars uses str_repeat("*", $row) inside a loop over the rows.

A few habits help a lot. Use clear names such as $row and $col instead of only $i and $j when you have two loops. Always think about the first and the last value of the counter: does the loop start at 0 or 1, and does it end with < or <=? Mistakes of one step too many or too few are the most common loop errors.

Example

<?php
$n = (int) trim(fgets(STDIN));

for ($i = 1; $i <= $n; $i++) {
    echo $i, " ";
}
echo "\n";

$total = 0;
$k = 1;
while ($k <= $n) {
    $total += $k;
    $k++;
}
echo "Sum: $total\n";

$j = 10;
do {
    echo "do-while runs once: $j\n";
    $j++;
} while ($j < 10);

for ($row = 1; $row <= 3; $row++) {
    echo str_repeat("*", $row), "\n";
}

foreach ([10, 20, 30] as $index => $value) {
    echo "$index: $value\n";
}

for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        continue;
    }
    if ($i > 7) {
        break;
    }
    echo "odd $i\n";
}

Input used: 5

Line by line

  1. The number 5 is read from the input.
  2. A for loop prints the numbers from 1 to 5 on one line.
  3. A while loop adds the numbers from 1 to 5 into $total.
  4. The do-while loop runs once, even though its condition is false from the start.
  5. A for loop with str_repeat prints a triangle of stars.
  6. foreach goes through an array with the index and the value.
  7. The last loop skips the even numbers with continue and stops after 7 with break.

Expected result

With the input 5, it prints:

1 2 3 4 5 
Sum: 15
do-while runs once: 10
*
**
***
0: 10
1: 20
2: 30
odd 1
odd 3
odd 5
odd 7

In the real world

Loops process data: a shop adds the price of every item in a cart, a script sends an email to every customer in a list, and a web page prints a table row for every record. Reading input until it ends is also a loop. Fast programs use loops carefully, because a loop inside a loop with big numbers is slow.

Common mistakes

  • An endless loop, because the counter never changes or the condition can never become false.
  • Off-by-one errors, such as < instead of <=.
  • Changing the array while going through it with foreach.
  • Forgetting that continue skips the step too in a while loop, so the counter must change before it.

Best practices

  • Use for when you know the count, foreach for arrays and while when you wait for a condition.
  • Keep the body of a loop short; move long work into a function.
  • Test the first and the last round in your head.
  • Avoid deep nesting; two levels are usually enough.

Summary

A loop repeats a block. for counts, while repeats as long as a condition is true, do-while always runs once, and foreach visits every item of an array. break leaves a loop and continue jumps to the next round. Check the first and last values of the counter to avoid off-by-one errors.

Quick check

1. Which loop always runs its body at least once?
2. What does continue do inside a loop?
3. How many times does for ($i = 0; $i < 5; $i++) run?
4. Which loop is the clearest way to visit every item of an array?

Key takeaways

  • for counts, while waits for a condition, do-while runs once at least and foreach visits arrays.
  • break and continue change the flow of a loop.
  • Check the first and last value of the counter to avoid off-by-one errors.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.