Skip to content

PHP Tutorial Loops

PHP foreach Loop

Lesson 95 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

foreach is the loop you will use most in PHP. It visits every item in an array, one after another.

index.php
PHP
<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
Output
OUTPUT
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.

index.php
PHP
<?php
$user = ["name" => "Ravi", "city" => "Goa", "age" => 31];

foreach ($user as $key => $value) {
    echo "$key: $value\n";
}
Output
OUTPUT
name: Ravi
city: Goa
age: 31

Indexed arrays have keys too

index.php
PHP
<?php
$tasks = ["Write code", "Test code"];

foreach ($tasks as $index => $task) {
    echo ($index + 1) . ". $task\n";
}
Output
OUTPUT
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.

index.php
PHP
<?php
$prices = [100, 200, 300];

foreach ($prices as $key => $price) {
    $prices[$key] = $price * 1.1;
}

echo implode(", ", $prices);
Output
OUTPUT
110, 220, 330

The reference form (foreach ($prices as &$price)) also works. Remember to unset($price) after the loop. See References.

Nested arrays

index.php
PHP
<?php
$products = [
    ["name" => "Pen", "price" => 10],
    ["name" => "Book", "price" => 250],
];

foreach ($products as $product) {
    echo $product["name"] . ": " . $product["price"] . "\n";
}
Output
OUTPUT
Pen: 10
Book: 250

Unpack items in the loop head

You can split each inner array directly in the loop header.

index.php
PHP
<?php
$points = [[1, 2], [3, 4]];

foreach ($points as [$x, $y]) {
    echo "x=$x y=$y\n";
}
Output
OUTPUT
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.

lightbulb
Prefer foreach for arrays
It is shorter than for, cannot go out of bounds, and makes the intent obvious. Use for only when you really need a counter.