Foreach Loop

JA JASWANT Updated 17 Oct 2026
8 min read ·Lesson 9 of 248
In this post

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

  1. After the first loop, $numbers is [2, 4, 6], and $n still references $numbers[2].
  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.
  3. The final array is [2, 4, 4] — the 6 is 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 foreach as the default loop for arrays and collections.
  • Use descriptive variable names: foreach ($products as $product).
  • Use $key => $value when 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 null with ?? [] when data may be missing.

Official reference: https://www.php.net/manual/en/control-structures.foreach.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about Foreach Loop and get answers drawn from it.

Signed-in readers only.