Foreach Loop
What Is a foreach Loop? In simple terms: foreach goes through an array (or another collection) one element at a time, giving you each value — and optionally its key — in turn. You do not need a counte
What Is a foreach Loop?
In simple terms: foreach goes through an array (or another collection) one element at a time, giving you each value — and optionally its key — in turn. You do not need a counter or to know how many elements there are.
Technically: foreach iterates over arrays and objects that implement Traversable (such as generators and iterators). On each iteration, it assigns the current element's value (and key) to the variables you name, and it stops automatically after the last element.
Why It Is the Most Common Loop in PHP
Most PHP data is stored in arrays: database rows, form fields, configuration, JSON from APIs. foreach is designed exactly for this:
- No index variable, so no off-by-one errors.
- Works with any keys — numeric, non-sequential, or string keys.
- Reads naturally: "for each product in products".
Syntax
foreach ($array as $value) {
// use $value
}
foreach ($array as $key => $value) {
// use $key and $value
}
Value Only
<?php
$languages = ['PHP', 'JavaScript', 'Python'];
foreach ($languages as $language) {
echo "I am learning $language\n";
}
Output
I am learning PHP
I am learning JavaScript
I am learning Python
On each iteration, $language receives the next value. The loop runs three times because the array has three elements.
Key and Value
<?php
$stock = [
'Keyboard' => 12,
'Mouse' => 0,
'Monitor' => 4,
];
foreach ($stock as $product => $quantity) {
$status = $quantity > 0 ? "$quantity in stock" : 'out of stock';
echo "$product: $status\n";
}
Output
Keyboard: 12 in stock
Mouse: out of stock
Monitor: 4 in stock
For associative arrays, the key carries meaning (the product name), so the $key => $value form is essential.
Keys in Indexed Arrays
<?php
$steps = ['Add to cart', 'Enter address', 'Pay'];
foreach ($steps as $index => $step) {
echo "Step " . ($index + 1) . ": $step\n";
}
Output
Step 1: Add to cart
Step 2: Enter address
Step 3: Pay
For indexed arrays, the key is the position starting at 0.
Iterating Over Records
Data from databases and APIs usually comes as an array of arrays — one inner array per record.
<?php
$orders = [
['id' => 1001, 'customer' => 'Asha', 'total' => 1250.00, 'paid' => true],
['id' => 1002, 'customer' => 'Bala', 'total' => 640.50, 'paid' => false],
['id' => 1003, 'customer' => 'Charu', 'total' => 3200.00, 'paid' => true],
];
$revenue = 0;
foreach ($orders as $order) {
$status = $order['paid'] ? 'Paid' : 'Pending';
printf("#%d %-6s ₹%8.2f %s\n", $order['id'], $order['customer'], $order['total'], $status);
if ($order['paid']) {
$revenue += $order['total'];
}
}
printf("Revenue from paid orders: ₹%.2f\n", $revenue);
Output
#1001 Asha ₹ 1250.00 Paid
#1002 Bala ₹ 640.50 Pending
#1003 Charu ₹ 3200.00 Paid
Revenue from paid orders: ₹4450.00
Each $order is one inner array, so its fields are read with $order['id'], $order['total'], and so on.
Destructuring in foreach
You can unpack each record directly into variables:
<?php
$orders = [
['id' => 1001, 'customer' => 'Asha', 'total' => 1250],
['id' => 1002, 'customer' => 'Bala', 'total' => 640],
];
foreach ($orders as ['id' => $id, 'customer' => $customer]) {
echo "Order $id belongs to $customer\n";
}
$points = [[0, 0], [3, 4]];
foreach ($points as [$x, $y]) {
echo "Point ($x, $y)\n";
}
Output
Order 1001 belongs to Asha
Order 1002 belongs to Bala
Point (0, 0)
Point (3, 4)
Only the keys you list are extracted. This makes loops over records more readable. See Array Destructuring.
Modifying the Array
foreach Works on a Copy of the Values
Changing $value inside the loop does not change the array:
<?php
$prices = [100, 200, 300];
foreach ($prices as $price) {
$price = $price * 2;
}
print_r($prices);
Output
Array
(
[0] => 100
[1] => 200
[2] => 300
)
$price is a copy of each element. Assigning to it only changes the copy.
Option 1: Write Back Using the Key
<?php
$prices = [100, 200, 300];
foreach ($prices as $index => $price) {
$prices[$index] = $price * 2;
}
print_r($prices);
Output
Array
(
[0] => 200
[1] => 400
[2] => 600
)
Option 2: Loop by Reference
Adding & makes $price a reference to the actual element:
<?php
$prices = [100, 200, 300];
foreach ($prices as &$price) {
$price = $price * 2;
}
unset($price);
print_r($prices);
Output
Array
(
[0] => 200
[1] => 400
[2] => 600
)
The unset($price) after the loop is essential — the next section explains why.
Option 3: Create a New Array
Often the clearest approach is not to modify the original at all:
<?php
$prices = [100, 200, 300];
$doubled = array_map(fn($price) => $price * 2, $prices);
print_r($doubled);
This produces the same doubled array while keeping $prices unchanged.
The Reference Pitfall
After a foreach by reference, the variable remains a reference to the last element. Reusing the same variable name in a later loop overwrites that element:
<?php
$numbers = [1, 2, 3];
foreach ($numbers as &$n) {
$n *= 2;
}
foreach ($numbers as $n) {
// just reading
}
print_r($numbers);
Output
Array
(
[0] => 2
[1] => 4
[2] => 4
)
Why the Last Element Changed
- After the first loop,
$numbersis[2, 4, 6], and$nstill references$numbers[2]. - The second loop assigns each value to
$n— which writes into$numbers[2]:- First iteration:
$numbers[2] = 2→[2, 4, 2] - Second iteration:
$numbers[2] = 4→[2, 4, 4] - Third iteration:
$numbers[2]is assigned its own current value,4.
- First iteration:
- The final array is
[2, 4, 4]— the6is lost.
Fix: Always call unset($variable) immediately after a reference loop. It removes the reference without changing the array.
Adding or Removing Elements During the Loop
foreach (by value) iterates over the array as it was when the loop started. Changes to the array inside the loop do not affect which elements are visited:
<?php
$queue = ['A', 'B'];
foreach ($queue as $item) {
echo "Processing $item\n";
if ($item === 'A') {
$queue[] = 'C'; // added to the array, but not visited by this loop
}
}
print_r($queue);
Output
Processing A
Processing B
Array
(
[0] => A
[1] => B
[2] => C
)
To process items that may be added during processing, use a while loop with array_shift() (see While Loop).
Removing elements by key during a value loop (unset($array[$key])) is safe in PHP — the loop continues with its original list of elements — but building a new, filtered array is usually clearer.
Iterating Over Objects
foreach also works on objects. For ordinary objects, it iterates over the public properties:
<?php
class Settings
{
public string $theme = 'dark';
public string $language = 'ta';
private string $apiKey = 'secret';
}
foreach (new Settings() as $name => $value) {
echo "$name = $value\n";
}
Output
theme = dark
language = ta
The private $apiKey is not visible from outside the class, so it is not included. Classes can control iteration completely by implementing Iterator or IteratorAggregate, and generators produce values for foreach one at a time without building a full array (see Iterators and PHP Generators).
Iterating Over Non-Arrays
<?php
$items = null;
foreach ($items as $item) {
echo $item;
}
echo "After loop\n";
Output
PHP Warning: foreach() argument must be of type array|object, null given in /path/script.php on line 4
After loop
Data that is "usually an array" — such as a decoded JSON field or a function result — may be null or false. Make sure it is an array before looping:
<?php
$items = null;
foreach ($items ?? [] as $item) {
echo $item;
}
echo "After loop\n";
$items ?? [] substitutes an empty array, so the loop simply runs zero times.
Alternative Syntax for Templates
<?php $tags = ['php', 'backend', 'tutorial']; ?>
<?php foreach ($tags as $tag): ?>
<a class="tag" href="/tag/<?= urlencode($tag) ?>">#<?= htmlspecialchars($tag) ?></a>
<?php endforeach; ?>
Output (HTML)
<a class="tag" href="/tag/php">#php</a>
<a class="tag" href="/tag/backend">#backend</a>
<a class="tag" href="/tag/tutorial">#tutorial</a>
urlencode() makes the tag safe inside a URL, and htmlspecialchars() makes it safe inside HTML. See Alternative Syntax.
Common Mistakes
Expecting $value Changes to Update the Array
Effect: The array stays unchanged.
Fix: Write back with $array[$key], loop by reference (and unset() afterwards), or build a new array.
Forgetting unset() After a Reference Loop
Effect: A later loop silently overwrites the last element.
Fix: unset($value); directly after every foreach (... as &$value).
Looping Over Possibly null Data
Effect: Warning and no iterations.
Fix: foreach ($data ?? [] as ...), or validate the data type first.
Running Queries Inside the Loop
Effect: One database query per element ("N+1 queries"), which makes pages slow.
Fix: Load all needed data with a single query before the loop.
Using the Wrong Variable Names for Key and Value
Effect: foreach ($users as $user => $id) puts the key in $user and the value in $id, the opposite of what the names suggest.
Fix: Remember the order: as $key => $value.
Best Practices
- Use
foreachas the default loop for arrays and collections. - Use descriptive variable names:
foreach ($products as $product). - Use
$key => $valuewhen the key carries meaning. - Prefer creating new arrays (or array functions) over modifying arrays in place; if you use references, always
unset()afterwards. - Guard against
nullwith?? []when data may be missing.
Official reference: https://www.php.net/manual/en/control-structures.foreach.php