PHP: Hypertext Preprocessor (original) (raw)
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.
foreach
can optionally get the key
of each element:
foreach (iterable_expression as $value) { statement_list }
foreach (iterable_expression as key=>key => key=>value) { statement_list }
The first form traverses the iterable given byiterable_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 tocustomize object iteration.
Example #1 Common foreach
usages
`<?php/* Example: value only */
$array = [1, 2, 3, 17];
foreach (
arrayasarray as arrayasvalue) {
echo "Current element of $array: $value.\n";
}/* Example: key and value */
$array = [
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
];
foreach (
arrayasarray as arrayaskey => $value) {
echo "Key: key=>Value:key => Value: 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 (
gridasgrid as gridasy => $row) {
foreach ($row as x=>x => 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 eitherarray destructuring via []
or by using the list() language construct as the value.
Note: Please note thatarray destructuring via
[]
is only possible as of PHP 7.1.0
In both of the following examples $a
will be set to the first element of the nested array and $b
will contain the second element:
`<?php
$array = [
[1, 2],
[3, 4],
];
foreach (
arrayas[array as [arrayas[a, $b]) {
echo "A: a;B:a; B: a;B:b\n";
}
foreach (
arrayaslist(array as list(arrayaslist(a, $b)) {
echo "A: a;B:a; B: a;B:b\n";
}
?>`
The above example will output:
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:
`<?php
$array = [
[1, 2, 3],
[3, 4, 6],
];
foreach (
arrayas[array as [arrayas[a, $b]) {
// Note that there is no $c here.
echo "$a $b\n";
}
foreach (
arrayas[,,array as [, , arrayas[,,c]) {
// Skipping over aanda and aandb
echo "$c\n";
}
?>`
The above example will output:
A notice will be generated if there aren't enough array elements to fill the list():
`<?php
$array = [
[1, 2],
[3, 4],
];
foreach (
arrayas[array as [arrayas[a, b,b, b,c]) {
echo "A: a;B:a; B: a;B:b; C: $c\n";
}
?>`
The above example will output:
Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C:
Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:
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 byreference.
<?php $arr = [1, 2, 3, 4]; foreach ($arr as &$value) { <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>l</mi><mi>u</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">value = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">u</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>value * 2; } // $arr is now [2, 4, 6, 8] unset($value); // break the reference with the last element ?>
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:
`<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) { value=value = value=value * 2;
}
// $arr is now [2, 4, 6, 8]
// without an unset($value), valueisstillareferencetothelastitem:value is still a reference to the last item: valueisstillareferencetothelastitem:arr[3]
foreach ($arr as key=>key => key=>value) {
// arr[3]willbeupdatedwitheachvaluefromarr[3] will be updated with each value from arr[3]willbeupdatedwitheachvaluefromarr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
?>`
The above example will output:
0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 ) 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 ) 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
Example #2 Iterate a constant array's values by reference
<?php foreach ([1, 2, 3, 4] as &$value) { <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>l</mi><mi>u</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">value = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">u</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>value * 2; } ?>
Found A Problem?
2 years ago
`An easier way to unpack nested array elements
$array = [
[1, 2],
[3, 4],
];
foreach ($array as [$a, $b]) {
echo "A: a;B:a; B: a;B:b\n";
}
`