Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops and Includes  ›  Lesson

foreach

Loops 13 minforeach walks an array item by item, giving a copy of each value and optionally its key, so changing the array means writing back through the key or looping by reference.

foreach

Pageturn's catalogue page must list every book with its price. You could count the array and index into it with for, but associative arrays have titles as keys, not numbers. foreach walks any array item by item, keys and all, and is the loop you will write most often in PHP.

The rule

foreach hands you a copy of each value — and its key if you ask.

<?php
$prices = ["Dune" => 9.99, "Emma" => 7.50, "Ulysses" => 12.00];

foreach ($prices as $price) {
    echo $price, "\n";                 // values only
}

foreach ($prices as $title => $price) {
    echo "$title: $price\n";            // Dune: 9.99, Emma: 7.5, ...
}

The two forms:

  • as $value: each round gives the next value.
  • as $key => $value: each round gives the key as well. For an indexed list the key is the position 0, 1, 2 and so on.

It works in the array's own order, needs no counter, and cannot run off the end.

The copy rule. $price is a copy. Changing it does nothing to the array:

foreach ($prices as $price) {
    $price = 0;          // the array is unchanged
}

To change the array, either write back through the key, $prices[$title] = $price * 2;, or loop by reference with &:

foreach ($prices as &$price) {
    $price = $price * 2;
}
unset($price);   // important: break the link

That unset matters. After the loop, $price is still linked to the last element. Reuse the name in a later loop and you will quietly overwrite that element. Writing back through the key avoids the problem entirely, which is why many teams prefer it.

foreach also handles the multi-dimensional catalogue naturally: foreach ($catalog as $book) { echo $book["title"]; }.

The shortcut

Before writing a foreach, ask two questions: do I need the key? and am I changing the array? Changing it → write back with $array[$key] = ....

Applying a 10% sale to every priceStep 1 of 4
  1. Need the key?

    Yes, to write back to the right title: as $title => $price.

Drills

Answer fast — trust the rule.

quick drill

In foreach ($prices as $title => $price), what is $title on the first round?

quick drill

After foreach ($prices as $price) { $price = 0; }, what is $prices["Dune"]?

quick drill

Which loop doubles every price inside the array itself?

quick drill

Why do you unset($price) after foreach ($prices as &$price)?

Remember

  • foreach hands you a copy of each value, and its key if you ask.
  • Shortcut: need the key? changing the array? then write back with $array[$key].
  • Trap: a by-reference loop leaves the variable linked to the last element until you unset it.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy did the sale not apply?

A developer writes foreach ($prices as $price) { $price = $price * 0.9; } and the prices do not change. Explain why and write a correct version.