The primary use of the foreach loop is to iterate through the items in an array.
Iterate through the elements of an indexed array:
$colors foreach |
In each iteration of the loop, the value of the current array element is assigned to the variable $x. The loop continues until it reaches the last element of the array.
The array above is an indexed array, where the first item has the key 0, the second has the key 1, and so on.
In contrast, associative arrays use named keys that you assign to them. When iterating through associative arrays, you might want to keep both the key and the value.
You can do this by specifying both the key and value in the foreach definition, as demonstrated below:
Output both the key and the value from the $members array:
$members foreach |
The foreach loop can also be used to iterate through the properties of an object:
Display the property names and values of the $myCar object:
class $myCar foreach |
Using the break statement, we can exit the loop even if it hasn’t reached the end.
Terminate the loop if $x is “blue”:
$colors foreach |
The continue statement allows us to skip the current iteration and proceed to the next one.
Skip to the next iteration if $x is “blue”:
$colors foreach |
When iterating through the array items, any modifications made to an array item will, by default, NOT impact the original array.
By default, modifying an array item will not affect the original array.
$colors foreach var_dump($colors); |
However, by using the & character in the foreach declaration, the array item is assigned by reference, meaning any changes made to the array item will also affect the original array.
By assigning the array items by reference, modifications will impact the original array.
$colors foreach var_dump($colors); |
The foreach loop syntax can also be expressed using the endforeach statement, as shown here:
Iterate through the elements of an indexed array:
$colors |