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 linkThat 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] = ....
Need the key?
Yes, to write back to the right title:
as $title => $price.
Drills
Answer fast — trust the rule.
In foreach ($prices as $title => $price), what is $title on the first round?
After foreach ($prices as $price) { $price = 0; }, what is $prices["Dune"]?
Which loop doubles every price inside the array itself?
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.
