foreach
(PHP 4, PHP 5, PHP 7, PHP 8)
The foreach construct provides an easy way to
iterate over arrays and Traversable objects.
foreach will issue an error when used with
a variable containing a different data type or with an uninitialized variable.
The first form traverses the iterable given by
iterable_expression. On each iteration, the value of
the current element is assigned to $value.
The second form will additionally assign the current element's key to
the $key variable on each iteration.
Note that foreach does not modify the internal array
pointer, which is used by functions such as current()
and key().
It is possible to
customize object iteration.
Example #1 Common foreach usages
<?php
/* Example: value only */
$array = [1, 2, 3, 17];
foreach ($array as $value) {
echo "Current element of \$array: $value.\n";
}
/* Example: key and value */
$array = [
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
];
foreach ($array as $key => $value) {
echo "Key: $key => Value: $value\n";
}
/* Example: multi-dimensional key-value arrays */
$grid = [];
$grid[0][0] = "a";
$grid[0][1] = "b";
$grid[1][0] = "y";
$grid[1][1] = "z";
foreach ($grid as $y => $row) {
foreach ($row as $x => $value) {
echo "Value at position x=$x and y=$y: $value\n";
}
}
/* Example: dynamic arrays */
foreach (range(1, 5) as $value) {
echo "$value\n";
}
?>
Note:
foreach does not support the ability to
suppress error messages using the
@.
Unpacking nested arrays
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
It is possible to iterate over an array of arrays and unpack the nested array
into loop variables by using either
array destructuring
via [] or by using the list() language
construct as the value.
Note:
Please note that
array destructuring
via [] is only possible as of PHP 7.1.0
When providing fewer variables than there are elements in the array,
the remaining elements will be ignored.
Similarly, elements can be skipped over by using a comma:
A notice will be generated if there aren't enough array elements to fill
the list():
foreach and references
It is possible to directly modify array elements within a loop by preceding
$value with &.
In that case the value will be assigned by
reference.
Warning
Reference to a $value of the last array element
remain even after the foreach loop. It is recommended
to destroy these using unset().
Otherwise, the following behavior will occur:
Example #2 Iterate a constant array's values by reference
<?php
foreach ([1, 2, 3, 4] as &$value) {
$value = $value * 2;
}
?>