PHP Foreach Loop: Array Traversal, Key-Value Pairs & References

In modern PHP development, arrays and collections represent the vast majority of application data (such as database query results, shopping cart items, and JSON API payloads). While traditional for loops require manual index counting, the foreach loop is custom-designed specifically for traversing arrays and objects. It manages internal array pointers automatically, guaranteeing zero off-by-one errors.

Two Forms of the foreach Loop

1. Value-Only Syntax

Used when you only need to process the data values and do not care about the array keys:

<?php
    $technologies = ["PHP 8", "MySQL", "Apache", "Docker", "Linux"];

    echo "<ul>";
    foreach ($technologies as $tech) {
        echo "<li>" . $tech . "</li>";
    }
    echo "</ul>";
?>

2. Key & Value Syntax (Associative Arrays)

When working with associative arrays or when you need the numeric index alongside the value:

<?php
    $studentProfile = [
        "Roll Number" => "BCA-2026-44",
        "Name"        => "Rohan Mehra",
        "Semester"    => "IV",
        "Major"       => "Computer Applications",
        "GPA"         => "3.92"
    ];

    echo "<table border='1' cellpadding='6'>";
    foreach ($studentProfile as $attribute => $val) {
        echo "<tr><th>" . $attribute . "</th><td>" . $val . "</td></tr>";
    }
    echo "</table>";
?>

Modifying Array Elements In-Place: By Reference (&)

By default, foreach assigns a copy of the array element to $value. If you alter $value, the original array remains unchanged. If you want to modify the array in-place, prefix $value with the reference operator &:

<?php
    $prices = [100, 200, 300];

    // Apply a 10% discount to all items directly in the array
    foreach ($prices as &$price) {
        $price = $price * 0.90; // Modifies the original array memory!
    }
    unset($price); // Best practice: breaks reference to avoid accidental overwrite!

    print_r($prices); // Outputs: [90, 180, 270]
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: Why is unset($value) recommended after modifying a foreach by-reference?
A: After the loop finishes, $value remains bound as a reference to the very last element of the array. If you subsequently use $value in another script location, you will unintentionally overwrite the last item of your array! Calling unset($value) immediately severs the pointer.

Interactive Student Practice Session

Exercise 18.1: Create an associative array of 5 countries and their capital cities. Use a foreach loop to display: "The capital of [Country] is [Capital]".

Exercise 18.2: Write a foreach loop that processes an array of numbers and computes both the total sum and the mathematical average.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!