← Back to Chapters

PHP Foreach Loop

? PHP Foreach Loop

? Quick Overview

The foreach loop in PHP is a simple and convenient way to iterate over arrays. Unlike traditional loops such as for or while, it directly accesses array elements without managing an index.

? Key Concepts

  • Designed specifically for arrays
  • Works with indexed and associative arrays
  • Can handle multidimensional arrays
  • Improves readability and reduces errors

⚙️ Syntax & Theory

? View Code Example
// Basic foreach syntax
foreach ($array as $value) {
    echo $value;
}
? View Code Example
// Foreach with key and value
foreach ($array as $key => $value) {
    echo $key . " => " . $value;
}

? Code Example 1: Indexed Array

? View Code Example
// Looping through an indexed array
<?php
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>

? Code Example 2: Associative Array

? View Code Example
// Looping through an associative array
<?php
$age = array("Peter" => 35, "John" => 30, "Doe" => 25);
foreach ($age as $name => $age_value) {
    echo "$name is $age_value years old.<br>";
}
?>

? Code Example 3: Multidimensional Array

? View Code Example
// Nested foreach loop with multidimensional array
<?php
$students = array(
    "Class A" => array("Alice", "Bob"),
    "Class B" => array("Charlie", "David")
);

foreach ($students as $class => $names) {
    echo "$class:<br>";
    foreach ($names as $student) {
        echo "- $student<br>";
    }
    echo "<br>";
}
?>

? Live Output / Explanation

Each foreach iteration fetches values directly from the array. For associative arrays, both keys and values are accessible. Nested loops allow traversal of complex data structures.

? Interactive Playground

Select a loop type to see how PHP "thinks" through the data structure.

Click a button to start simulation...

? Interactive Visualization

The flow below conceptually represents how foreach processes array elements sequentially:

Array ➜ Element ➜ Execute Block ➜ Next Element

? Use Cases

  • Displaying lists of data from arrays
  • Processing form input values
  • Reading database result sets
  • Handling configuration arrays

✅ Tips & Best Practices

  • Prefer foreach for array traversal for clarity.
  • Use meaningful variable names for keys and values.
  • Avoid modifying the array inside the loop.

? Try It Yourself

  • Create an array of your favorite colors and print them using foreach.
  • Build an associative array of students and marks and display formatted output.
  • Create a multidimensional array and loop through it using nested foreach.