The Homepage of Nis Bornoe

PHP: Foreach Loop Tutorial

Page updated: November 5, 2023

In PHP, the foreach loop is a specialized loop that is used to iterate over arrays and objects. It allows you to loop through each key/value pair in an array or each property in an object.

Syntax

foreach ($array as $value) {
    // Code to be executed
}

Example

Consider the following PHP code that demonstrates the usage of a foreach loop:

<?php
    $colors = array("Red", "Green", "Blue");
    foreach ($colors as $value) {
        echo "$value <br>";
}
?>

This code will print each color from the array $colors on a new line.

Example for associative arrays

Consider the following PHP code that demonstrates the usage of a foreach loop for associative arrays:

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
    foreach ($age as $key => $value) {
    // Code to be executed
}

Use Cases

  • When you need to iterate over the elements of an array without explicitly knowing the array's length or indices.
  • For performing operations that involve every element of an array, such as displaying data or processing items in an array.

Cautions

  • Ensure that the variable you're iterating over is indeed an array or an object to prevent errors.
  • Be cautious when modifying the array or object within the foreach loop to avoid unexpected behavior.