foreach is the loop you will use most in PHP. It visits every item in an array, one after another.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
Apple
Banana
Cherry
Read it as: “for each item in $fruits, call it $fruit and run the block.” You do not manage a counter, and you cannot go past the end.
Keys and values
Add $key => to get the key as well.
<?php
$user = ["name" => "Ravi", "city" => "Goa", "age" => 31];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
name: Ravi
city: Goa
age: 31
Indexed arrays have keys too
<?php
$tasks = ["Write code", "Test code"];
foreach ($tasks as $index => $task) {
echo ($index + 1) . ". $task\n";
}
1. Write code
2. Test code
Change the original array
A normal foreach works on a copy of each item. To change the array itself, loop by reference with &, or write back using the key.
<?php
$prices = [100, 200, 300];
foreach ($prices as $key => $price) {
$prices[$key] = $price * 1.1;
}
echo implode(", ", $prices);
110, 220, 330
The reference form (foreach ($prices as &$price)) also works. Remember to unset($price) after the loop. See References.
Nested arrays
<?php
$products = [
["name" => "Pen", "price" => 10],
["name" => "Book", "price" => 250],
];
foreach ($products as $product) {
echo $product["name"] . ": " . $product["price"] . "\n";
}
Pen: 10
Book: 250
Unpack items in the loop head
You can split each inner array directly in the loop header.
<?php
$points = [[1, 2], [3, 4]];
foreach ($points as [$x, $y]) {
echo "x=$x y=$y\n";
}
x=1 y=2
x=3 y=4
foreach on objects
foreach also goes through the public properties of an object, and through collections that implement Traversable.
An empty array is fine
If the array is empty, the loop body simply never runs. There is no error.
Prefer foreach for arrays
for, cannot go out of bounds, and makes the intent obvious. Use for only when you really need a counter.