PHP Foreach Loop
A foreach loop runs a block once for each value in an array. It needs no counter and no test in a header.
Printing each value
Foreach takes each value in order. The $color variable holds one color per round.
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "\n";
}Printing the index and the value
The $key variable holds the index number. The $value variable holds the color at that index.
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $key => $value) {
echo $key . ": " . $value . "\n";
}The array stays unchanged
Each copied value is doubled inside the loop. The print_r output still shows the first values.
<?php
$numbers = [1, 2, 3];
foreach ($numbers as $number) {
$number = $number * 2;
}
print_r($numbers);Example
<?php
$items = ["Milk", "Bread", "Eggs"];
$number = 1;
foreach ($items as $item) {
echo $number . ". " . $item . "\n";
$number++;
}Key points
- Foreach visits every value in an array in order.
- The value variable holds one array value in each round.
- Writing $key => $value gives the index in $key and the value in $value.
- Foreach works on a copy of each value.
- Changes to that copy leave the array unchanged.
In this example, a counter starts at 1. Each round prints the counter, a dot and one item from the list. The counter grows by one after each line, so the lines come out numbered in order.
Note
An indexed array uses numbers as its keys.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
Inside a foreach loop, a program doubles the value variable. What happens to the array?