foreach
The "foreach" keyword is a looping construct in PHP that is used to iterate over arrays and objects. In this article, we will explore the syntax and usage of
The PHP foreach Loop
foreach is PHP's dedicated loop for iterating over arrays and objects. Unlike a for loop, it does not need a counter or an index — it walks through every element automatically, one at a time, which makes it the most common and least error-prone way to process a collection in PHP.
This chapter covers the two foreach forms, iterating by reference, unpacking nested arrays with list(), the most common gotcha, and when you would reach for foreach over the other PHP loops.
Syntax
foreach has two forms.
Value only — when you only care about each element's value:
foreach ($array as $value) {
// do something with $value
}Key and value — when you also need the array key (essential for associative arrays):
foreach ($array as $key => $value) {
// do something with $key and $value
}On each pass, PHP copies the current element into $value (and its key into $key), then advances to the next element until the array is exhausted.
Iterating an indexed array
Iterating an associative array
With the $key => $value form you get both halves of each pair:
<?php
$person = ["name" => "John", "age" => 30, "city" => "New York"];
foreach ($person as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
// Output:
// name: John
// age: 30
// city: New YorkModifying values by reference
By default $value is a copy, so changing it inside the loop does not affect the original array. Prefix it with & to iterate by reference and write changes back:
<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
$price *= 2; // modifies the array in place
}
unset($price); // important: break the reference
print_r($prices);
// Output:
// Array
// (
// [0] => 20
// [1] => 40
// [2] => 60
// )Gotcha: always
unset($price)after a by-reference loop. The variable still points at the last element, so a later assignment to$price— or a secondforeachreusing the name — would silently corrupt the array.
Unpacking nested arrays with list()
When each element is itself an array, you can destructure it inline using list() (or the short [] syntax in PHP 7.1+):
<?php
$points = [[1, 2], [3, 4], [5, 6]];
foreach ($points as [$x, $y]) {
echo "x=$x, y=$y" . PHP_EOL;
}
// Output:
// x=1, y=2
// x=3, y=4
// x=5, y=6When to use foreach
- Use
foreachfor any array or iterable where you want every element — it is the clearest choice and cannot run off the end of the array. - Use a
forloop when you need fine control over the counter (skipping, stepping by 2, counting down). - Use
whilewhen the number of iterations isn't known in advance and depends on a condition.
You can also exit a foreach early with break or skip an iteration with continue, exactly as in other loops.