Table of Contents
Introduction
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Syntax of the foreach Loop
The syntax of the foreach loop is given as:
Syntax
Theforeach loop.
1foreach ($array as $value) {
2 statement(s);
3}
where
$arrayis the name of the array we want to loop through.$valueis a variable name that PHP uses to store the value of the current array item.
In order to be able to directly modify array elements within the loop, precede $value with the & character. In that case the value will be assigned by reference.
An alternative syntax of the foreach loop that works with associative arrays is given as:
Syntax
Theforeach loop (alternative syntax).
1foreach ($array as $key => $value) {
2 statement(s);
3}
where, in addition to the $array and $value defined earlier, we have
$keyis an optional variable name that PHP uses to store the key of the current array item.
ADVERTISEMENT
Using the foreach Loop
Example
Using theforeach loop on an array.
1<?php
2 $cars = array("Volvo", "BMW", "Toyota", "Lexus");
3 foreach ($cars as $value) {
4 echo "$value <br>";
5 }
6?>
Volvo
BMW
Toyota
Lexus
To directly modify array elements within the loop, we precede $value with the & character. In the following example, the character X is appended to each item of the array.
Example
Using theforeach loop and modifying an array.
1<?php
2 $cars = array("Volvo", "BMW", "Toyota", "Lexus");
3 foreach ($cars as &$value) {
4 $value .= "X";
5 echo "$value <br>";
6 }
7 print_r($cars); // modified
8?>
VolvoX
BMWX
ToyotaX
LexusX
Array ( [0] => VolvoX [1] => BMWX [2] => ToyotaX [3] => LexusX )
If we did not precede $value with &, the original array will not be modified.
Example
Using theforeach loop on an array without modification.
1<?php
2 $cars = array("Volvo", "BMW", "Toyota", "Lexus");
3 foreach ($cars as $value) {
4 $value .= "X";
5 echo "$value <br>";
6 }
7 print_r($cars); // not modified
8?>
VolvoX
BMWX
ToyotaX
LexusX
Array ( [0] => Volvo [1] => BMW [2] => Toyota [3] => Lexus )
Example
Using theforeach loop on an associative array.
1<?php
2 $age = array("John"=>"36", "Lex"=>"24", "Tim"=>"33", "Julian"=>"28");
3 foreach($age as $item => $val) {
4 echo "$item: $val<br>";
5 }
6?>
John: 36
Lex: 24
Tim: 33
Julian: 28