Loops, Especially foreach

Do it for every item in the list

9 min read

Remember the arrays lesson, where adding up a price list meant writing out every index by hand? You were promised a better way. Here it is.

foreach: the web developer's favorite loop

A loop repeats a block of code. PHP has several kinds, but for websites one towers above the rest: foreach, which visits every item in an array, one at a time.

<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "<li>" . $color . "</li>";
}
?>

Read it as: for each item in $colors, calling the current item $color, run the block. The block runs three times, once per item, and outputs:

<li>red</li>
<li>green</li>
<li>blue</li>

Stop and appreciate this: the loop does not care whether the array holds 3 items or 3000. This is the exact pattern behind every product grid, comment thread, and search results page on the web. An array of data goes in, a repeated chunk of HTML comes out.

foreach with keys

Looping over an associative array? A slightly longer form hands you the key and the value together:

<?php
$scores = ["Ada" => 95, "Grace" => 88, "Alan" => 91];
foreach ($scores as $name => $score) {
    echo "<p>" . $name . " scored " . $score . "</p>";
}
?>

Each trip through the loop, $name holds the current key and $score holds its value: Ada scored 95, Grace scored 88, Alan scored 91.

Solving the price problem properly

<?php
$prices = [19.99, 4.50, 32.00, 7.25];
$total = 0;
foreach ($prices as $price) {
    $total += $price;
}
echo "Cart total: $" . $total;
?>

Start the total at zero, add each price as the loop visits it, and by the end $total holds 63.74. Add fifty more prices to the array and this code does not change by a single character.

The other loops, briefly

You will also meet for, which counts through numbers, and while, which repeats as long as a condition stays true:

<?php
for ($i = 1; $i <= 3; $i++) {
    echo "Lap " . $i . " ";
}
?>

This prints Lap 1 Lap 2 Lap 3. The for loop sets up a counter, keeps going while the condition holds, and bumps the counter each lap using the ++ you met in the math lesson. It is handy when you need numbers rather than items, but honestly, in day-to-day web work, foreach will be your loop ninety percent of the time.

One caution about while loops: if the condition never becomes false, the loop never stops, which is called an infinite loop. It is a rite of passage; every programmer writes one eventually. foreach cannot do this, which is one more reason beginners should love it.

Quick check

Q1 An array holds 4 items. How many times does the body of foreach ($items as $item) run?

Q2 In foreach ($scores as $name => $score), what does $name hold on each pass?

Want to save your progress? It's free.

Create a free account