PHP foreach Loop [With Examples]

PHP foreach Loop

Looping over arrays and iterating over an object’s attributes form the foundation of a lot of application logic.

The foreach construct in PHP can do both and is a crucial tool for building your application logic.

PHP foreach Syntax

The syntax for a foreach construct in PHP is as follows:

foreach (iterable_expression as $value) {
    # statement(s)
}

Or, if you also wish to access the array key as well:

foreach (iterable_expression as $key => $value) {
    # statement(s)
}

Note that:

  • iterable_expression is the variable or value to be iterated over.
    • Only arrays or objects are supported; an error will be generated otherwise
  • $value will be the name of the variable in the iteration which holds the current item from the iterable_expression
    • $key is either one of two values depending on whether an object or array is passed to foreach
      • If iterating over an array, it is the index (position) of the current item being iterated over, starting at 0
      • If iterating over an associative array, it is the array key – the name of the item in the array
      • If iterating over an object, it is the name of the current object property or attribute being iterated over
  • statement(s) is the PHP code to execute for each iteration (for each item in the array or attribute of the object)
  • $value will remain set after the foreach loop has completed (with the value from the last iteration)! Make sure you use it if you intend to use it, or unset it, so it doesn’t interfere with future code!

foreach Examples

Iterating (Looping) over an Array

$array = array("red", "blue", "green", "purple");

foreach ($array as &$value) {
    $value = $value . ' car'; # Add ' car' to each $value in the array
}

# $array is now array("red car", "blue car", "green car", "purple car")

unset($value); # unset $value as it will be left over from the loop with the last value iterated

Note here that $value is preceded by an & (ampersand). This is optional and means that the variable is passed as a reference, which means any change made to it will be reflected in the original array. Otherwise, if $value is modified in the foreach statements, the original value will remain unaltered.

Iterating (Looping) over an Array (with Key)

$array = array("red", "blue", "green", "purple");

foreach ($array as $key => &$value) {
    $value = $key . ' ' .$value . ' car'; # Add the $key, followed by a space before the $value, and add ' car' to the end of each $value in the array
}

# $array is now array("0 red car", "1 blue car", "2 green car", "3 purple car")

unset($value); # unset $value as it will be left over from the loop with the last value iterated

The same method works for associative arrays:

$array = array("first" => "red", "second" => "blue", "third" => "green", "fourth" => "purple");

foreach ($array as $key => &$value) {
    $value = $key . ' ' .$value . ' car'; # Add the $key, followed by a space before the $value, and add ' car' to the end of each $value in the array
}

# $array is now array("first" => "first red car", "second" => "second blue car", "third" => "third green car", "fourth" => "fourth purple car")

unset($value); # unset $value as it will be left over from the loop with the last value iterated

Iterating over a Multidimensional Array

foreach loops can be nested for iterating over arrays that contain arrays (multidimensional arrays) or objects containing objects:

# An array containing a list of vehicles, each vehicle entry gives some details about the vehicle
$array = [
    ["red", "car"],
    ["blue", "bike"],
    ["green", "bus"],
    ["purple", "boat"],
];

foreach ($array as $vehicle) {
    foreach ($vehicle as $detail) {
        echo $detail . " "; # Output each detail in the array representing the vehicle, separated by a space
    }
    echo ", "; # Output a comma between vehicles
}

#Will output "red car, blue bike, green bus, purple boat, "

Note that in the above example, the array is defined in shorthand using [] rather than array().

Using list() with Multidimensional Arrays

Shortcut the above using the PHP list() function to unpack the nested array:

$array = [
    ["red", "car"],
    ["blue", "bike"],
    ["green", "bus"],
    ["purple", "boat"],
];

foreach ($array as list($colour, $type)) {
    // $colour contains the first element of the nested array - the vehicle colour
    // and $type contains the second element - the vehicle type
    echo "Colour: $colour, Type: $type \n"; # \n outputs a new line
}

This will output:

Colour: red, Type: car 
Colour: blue, Type: bike 
Colour: green, Type: bus 
Colour: purple, Type: boat 

While you’re here, check out our other PHP articles, or check out the official foreach documentation.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *