foreach
foreach traverses an array or iterable, optionally providing keys. By-value iteration does not rebind array entries, while by-reference iteration can modify them; object values can still refer to shared objects.
Inspect keys and values during traversal, including the consequences of references.
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"]; }.