The Foreach Construct
The foreach
construct allows you to sequentially iterate over array elements.
It works with arrays and objects that implement the Traversable
interface.
There are two syntax variants: for iterating over values only and for iterating over keys and values.
Syntax
foreach (array as $value) {
// loop body
}
foreach (array as $key => $value) {
// loop body
}
Example
Simple iteration over array elements:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $value) {
echo $value . '<br>';
}
?>
Code execution result:
1
2
3
4
5
Example
Iterating over an array with getting keys and values:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
foreach ($arr as $key => $value) {
echo "$key: $value<br>";
}
?>
Code execution result:
a: 1
b: 2
c: 3
Example
Using a reference to modify array elements:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as &$value) {
$value *= 2;
}
unset($value);
print_r($arr);
?>
Code execution result:
[2, 4, 6, 8, 10]
See Also
-
the
array_map
function,
which applies a callback function to all elements of an array -
the
array_walk
function,
which applies a user-defined function to each element of an array