PHP Mastery Tutorial 0/120 lessons ~6 min read Lesson 17

    Mastering the foreach Loop

    Master the PHP foreach loop — indexed and associative arrays, multidimensional data, references, break/continue, and real-world API and cart patterns.

    Course progress0%
    Focus
    26 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Mastering the foreach Loop

    Introduction

    Imagine you have a shopping cart containing 100 products.

    Would you access every product like this?

    php
    echo $products[0];
    echo $products[1];
    echo $products[2];
    ...
    echo $products[99];

    Of course not.

    This approach is repetitive, difficult to maintain, and nearly impossible to scale.

    Instead, PHP provides one of its most powerful looping constructs:

    foreach

    The foreach loop is specially designed to iterate through arrays and iterable objects.

    Whenever you're working with:

    • Database records
    • JSON responses
    • API data
    • Shopping carts
    • User lists
    • Product catalogs
    • Configuration arrays

    You'll most likely use foreach.

    If you plan to become a Laravel developer, mastering foreach is essential because Laravel makes extensive use of arrays and collections.

    What is a foreach Loop?

    A foreach loop automatically visits every element in an array.

    Unlike a for loop, you don't need:

    • A counter
    • An index
    • A loop condition
    • An increment statement

    PHP handles all of these internally.

    This makes your code cleaner, shorter, and less error-prone.

    Syntax

    php
    foreach ($array as $value) {
    // Code
    }

    PHP automatically takes one element at a time and stores it in $value.

    Example 1: Loop Through an Indexed Array

    php
    <?php
    $colors = ["Red", "Green", "Blue"];
    foreach ($colors as $color) {
    echo $color . "<br>";
    }

    Output:

    Red
    Green
    Blue

    PHP automatically moves through every element.

    No index variables are required.

    How foreach Works

    Internally, PHP performs something similar to:

    Iteration 1

    $color = "Red"

    Iteration 2

    $color = "Green"

    Iteration 3

    $color = "Blue"

    After the last element, the loop ends automatically.

    Real-World Example: Product Catalog

    php
    <?php
    $products = [
    "Laptop",
    "Keyboard",
    "Mouse",
    "Monitor"
    ];
    foreach ($products as $product) {
    echo $product . "<br>";
    }

    Output:

    Laptop
    Keyboard
    Mouse
    Monitor

    This pattern is common in e-commerce applications.

    Associative Arrays

    Associative arrays store data as key-value pairs.

    Example:

    php
    $user = [
    "name" => "Rahul",
    "email" => "rahul@example.com",
    "city" => "Hyderabad"
    ];

    To access both keys and values:

    php
    foreach ($user as $key => $value) {
    echo $key . " : " . $value . "<br>";
    }

    Output:

    name : Rahul
    email : rahul@example.com
    city : Hyderabad

    Understanding Keys and Values

    Every associative array has:

    • A key
    • A value

    Example:

    php
    "name" => "Rahul"

    Here:

    Key:

    name

    Value:

    Rahul

    The foreach loop can access both simultaneously.

    Real-World Example: Employee Details

    php
    <?php
    $employee = [
    "ID" => 1001,
    "Name" => "John",
    "Department" => "IT",
    "Salary" => 75000
    ];
    foreach ($employee as $field => $value) {
    echo $field . " : " . $value . "<br>";
    }

    Output:

    ID : 1001
    Name : John
    Department : IT
    Salary : 75000

    Looping Through Multidimensional Arrays

    Professional applications rarely use simple arrays.

    Most applications use arrays containing multiple records.

    Example:

    php
    <?php
    $employees = [
    [
    "name" => "Rahul",
    "department" => "HR"
    ],
    [
    "name" => "Priya",
    "department" => "Finance"
    ],
    [
    "name" => "John",
    "department" => "IT"
    ]
    ];

    Loop through them:

    php
    foreach ($employees as $employee) {
    echo $employee["name"] . " - ";
    echo $employee["department"] . "<br>";
    }

    Output:

    Rahul - HR
    Priya - Finance
    John - IT

    This is one of the most common patterns in enterprise applications.

    Nested foreach

    Sometimes arrays contain other arrays.

    Example:

    php
    <?php
    $classroom = [
    "Class A" => ["Rahul", "John"],
    "Class B" => ["Priya", "Amit"]
    ];
    foreach ($classroom as $class => $students) {
    echo "<h3>$class</h3>";
    foreach ($students as $student) {
    echo $student . "<br>";
    }
    }

    Output:

    Class A
    Rahul
    John
    
    Class B
    Priya
    Amit

    Nested foreach loops are widely used for hierarchical data.

    Modifying Values Using References

    Normally, foreach works on copies of values.

    php
    foreach ($numbers as $number)

    Changing $number does not change the original array.

    Example:

    php
    <?php
    $numbers = [1, 2, 3];
    foreach ($numbers as $number) {
    $number *= 2;
    }
    print_r($numbers);

    Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
    )

    The original array remains unchanged.

    Using References (&)

    To modify the original array:

    php
    <?php
    $numbers = [1, 2, 3];
    foreach ($numbers as &$number) {
    $number *= 2;
    }
    unset($number);
    print_r($numbers);

    Output:

    Array
    (
        [0] => 2
        [1] => 4
        [2] => 6
    )

    Notice the use of:

    php
    &

    This creates a reference instead of a copy.

    Why unset() Is Important

    After looping by reference, always remove the reference.

    php
    unset($number);

    Without unset(), $number continues pointing to the last array element, which can lead to unexpected bugs if reused later.

    This is a subtle issue that experienced PHP developers are careful to avoid.

    Real-World Example: Displaying Database Results

    php
    <?php
    $users = [
    [
    "id" => 1,
    "name" => "Rahul"
    ],
    [
    "id" => 2,
    "name" => "Priya"
    ]
    ];
    foreach ($users as $user) {
    echo $user["id"];
    echo " - ";
    echo $user["name"];
    echo "<br>";
    }

    This resembles how data is displayed after fetching rows from a database.

    Real-World Example: API Response

    Imagine an API returns:

    php
    $response = [
    "success" => true,
    "products" => [
    ["name" => "Laptop"],
    ["name" => "Mouse"],
    ["name" => "Keyboard"]
    ]
    ];

    Process it:

    php
    foreach ($response["products"] as $product) {
    echo $product["name"] . "<br>";
    }

    Most REST API integrations use this pattern.

    Real-World Example: Shopping Cart

    php
    <?php
    $cart = [
    [
    "name" => "Laptop",
    "price" => 70000
    ],
    [
    "name" => "Mouse",
    "price" => 800
    ]
    ];
    $total = 0;
    foreach ($cart as $item) {
    $total += $item["price"];
    }
    echo "Total = ₹" . $total;

    Output:

    Total = ₹70800

    Using break with foreach

    php
    foreach ($products as $product) {
    if ($product == "Keyboard") {
    echo "Found";
    break;
    }
    }

    The loop stops immediately after finding the product.

    Using continue

    php
    foreach ($users as $user) {
    if (!$user["active"]) {
    continue;
    }
    echo $user["name"] . "<br>";
    }

    Inactive users are skipped.

    Performance Considerations

    The foreach loop is highly optimized for iterating arrays.

    In most cases:

    • Prefer foreach over for when processing arrays.
    • Avoid expensive operations inside the loop.
    • Fetch required data before entering the loop.
    • Keep each iteration lightweight.

    Readability is usually more important than micro-optimizations.

    Best Practices

    Use Meaningful Variable Names

    Instead of:

    php
    foreach ($users as $u)

    Write:

    php
    foreach ($users as $user)

    Clear names improve readability.

    Don't Modify Arrays Unless Necessary

    Use references (&) only when you intentionally need to update the original array. Otherwise, iterate by value.

    Keep Loops Focused

    A foreach loop should perform one main task.

    If the logic becomes too large, extract it into a function.

    Use Strict Comparisons

    When comparing values inside loops, prefer === over == to avoid unexpected type juggling.

    Common Mistakes

    Using for Instead of foreach

    When iterating over arrays, foreach is usually simpler and less error-prone.

    Forgetting unset() After References

    Always call:

    php
    unset($value);

    after a reference-based foreach.

    Changing the Array Structure While Iterating

    Adding or removing elements from an array during iteration can make the code harder to understand and may lead to unexpected behavior.

    Writing Too Much Logic Inside the Loop

    If your loop spans dozens of lines, consider moving some work into helper functions. Small, focused loops are easier to read and test.

    Hands-on Exercise

    Create a PHP program that:

    1. Prints all student names from an indexed array.
    2. Displays all employee details from an associative array.
    3. Loops through a multidimensional array of products.
    4. Calculates the total price of items in a shopping cart.
    5. Doubles every number in an array using references.
    6. Skips inactive users using continue.
    7. Stops searching after finding a specific product using break.
    8. Displays product names from a simulated API response.

    Try solving each exercise before looking for the solution. Practicing these scenarios will make foreach feel natural.

    Summary

    The foreach loop is the preferred way to iterate through arrays in PHP.

    It eliminates the need for manual counters and makes your code cleaner, safer, and easier to maintain.

    Whether you're processing database rows, reading API responses, generating reports, or building Laravel applications, foreach will become one of the tools you use most often.

    Key Takeaways

    • foreach is designed specifically for arrays and iterable objects.
    • It automatically visits every element without requiring an index.
    • Use key => value syntax for associative arrays.
    • Nested foreach loops handle multidimensional arrays.
    • Use references (&) only when modifying the original array.
    • Always call unset() after a reference-based foreach.
    • Combine foreach with break and continue for efficient processing.
    • Keep loops simple, readable, and focused on one responsibility.

    Next Lesson

    Functions in PHP — learn how to create reusable blocks of code with parameters, return values, and the patterns professional developers use every day.

    Continue at /learn/php/functions.

    Ready to mark this lesson complete?Track your journey across the entire course.