W3docs

PHP Looping: Understanding the Foreach Loop

The foreach loop is a powerful and essential tool for PHP developers. It provides a convenient way to iterate over arrays and objects in a loop. In this

The foreach loop is the most convenient way to iterate over arrays and objects in PHP. Unlike the for loop, it requires no counter and no length calculation — it simply walks through every element in order. This guide covers its syntax, how to read both keys and values, modifying elements by reference, nested loops, and the common gotchas that trip up beginners.

What is the Foreach Loop?

The foreach loop is a loop designed specifically for arrays and objects. It traverses a collection and hands you each element one at a time, so you never have to manage an index variable or worry about going out of bounds. This makes it ideal for indexed arrays, associative arrays, and iterable objects alike.

It comes in two forms:

  • foreach ($array as $value) — when you only need each value.
  • foreach ($array as $key => $value) — when you also need each key.

If you need a counter, a step other than 1, or to loop a fixed number of times that isn't tied to an array, reach for a for or while loop instead. See PHP Loops for an overview of all loop types.

Syntax of the Foreach Loop

The syntax of the foreach loop is simple and straightforward. It consists of the foreach keyword, followed by a set of parentheses that define the array or object to be looped over. Within the parentheses, you define a variable to hold the value of each element as the loop iterates.

Here's an example of the syntax for the foreach loop:

PHP Syntax of the Foreach Loop

foreach ($array as $value) {
    // code to be executed for each element
}

In this example, $array is the array or object that you want to loop over, and $value is the variable that holds the value of each element as the loop iterates.

For associative arrays or objects where you need both the key and the value, you can use the => operator:

foreach ($array as $key => $value) {
    // code to be executed for each element
}

Looping with keys and values

When an array maps keys to values, the $key => $value form gives you both at once:

<?php

$capitals = array(
    "France"  => "Paris",
    "Japan"   => "Tokyo",
    "Egypt"   => "Cairo"
);

foreach ($capitals as $country => $city) {
    echo "The capital of $country is $city.\n";
}

This prints:

The capital of France is Paris.
The capital of Japan is Tokyo.
The capital of Egypt is Cairo.

Modifying array elements by reference

By default foreach copies each value, so assigning to the loop variable does not change the original array. Prefix the value with & to iterate by reference and modify elements in place:

<?php

$prices = array(10, 20, 30);

foreach ($prices as &$price) {
    $price *= 2;          // changes the real array element
}
unset($price);             // important: break the reference

print_r($prices);

This prints:

Array
(
    [0] => 20
    [1] => 40
    [2] => 60
)

Gotcha: always unset($price) after a by-reference loop. The variable keeps pointing at the last element, and reusing it in a later loop silently corrupts your data — one of the most common PHP bugs.

Usage of the Foreach Loop

The foreach loop is used to traverse arrays and objects. It allows you to access each element of the array or object one by one, and perform a specific action for each element. For example, you could use the foreach loop to print out all the elements of an array, or to perform a calculation for each element in an object.

Here's an example of how to use the foreach loop in PHP:

PHP Usage of the Foreach Loop

php— editable, runs on the server

In this example, we've created an array of colors, and then used the foreach loop to print out each color in the array. The loop iterates over the elements of the $colors array, and for each iteration, the value of the current element is assigned to the $color variable.

Examples of the Foreach Loop

The foreach loop is a flexible tool that can be used in a variety of ways. Here are a few examples of how you can use the foreach loop in your PHP code:

  • Printing out the elements of an array:

PHP Printing out the elements of an array by using foreach loop

php— editable, runs on the server
  • Calculating the sum of an array:

PHP Calculating the sum of an array by using foreach loop

php— editable, runs on the server
  • Accessing the properties of an object:

PHP Accessing the properties of an object in foreach loop

<?php

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = array(
    new Person("John", 25),
    new Person("Jane", 30),
    new Person("Jim", 35)
);

foreach ($people as $person) {
    echo "Name: " . $person->name . ", Age: " . $person->age . "<br>";
}

?>

In this example, we've created a Person class with two properties, name and age. We then created an array of Person objects, and used the foreach loop to access the properties of each Person object. The loop iterates over the elements of the $people array, and for each iteration, the value of the current Person object is assigned to the $person variable. We then use the -> operator to access the properties of the Person object.

Nested Foreach Loops

To work through a multidimensional array, nest one foreach inside another. The outer loop walks the rows, and the inner loop walks each row's columns:

<?php

$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6)
);

foreach ($matrix as $row) {
    foreach ($row as $cell) {
        echo $cell . " ";
    }
    echo "\n";   // new line after each row
}

This prints:

1 2 3
4 5 6

Controlling the Loop with break and continue

Inside a foreach you can use break to stop the loop early and continue to skip to the next element:

<?php

$numbers = array(1, 2, 3, 4, 5, 6);

foreach ($numbers as $number) {
    if ($number % 2 !== 0) {
        continue;        // skip odd numbers
    }
    if ($number > 4) {
        break;           // stop once we pass 4
    }
    echo $number . " ";
}

This prints:

2 4

The odd numbers 1, 3, and 5 are skipped by continue; 2 and 4 are printed; and when the loop reaches the even number 6 (greater than 4), break stops it entirely.

Conclusion

The foreach loop is an essential tool for PHP developers. It provides a convenient and easy-to-use way to iterate over arrays and objects, allowing you to access and perform actions on each element. Whether you're printing out the elements of an array, calculating sums, or accessing object properties, the foreach loop is a versatile tool that can be used in a variety of ways.

So why not try using the foreach loop in your PHP code today, and see how it can simplify and streamline your development process?

Practice

Practice
What does the PHP 'foreach' loop do?
What does the PHP 'foreach' loop do?
Was this page helpful?