PHP Foreach Loop

PHP Foreach Loop

The foreach loop is designed specifically for iterating over arrays and objects — the loop you will use most often in PHP.

1 - Indexed Array

$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

2 - Associative Array

$person = ["name" => "Alice", "age" => 30, "city" => "Paris"];

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

3 - Array of Objects

$users = [
    ["name" => "Alice", "role" => "admin"],
    ["name" => "Bob",   "role" => "editor"],
];

foreach ($users as $user) {
    echo "{$user["name"]} is an {$user["role"]}<br>";
}

4 - Modifying Values by Reference

$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as &$num) {
    $num *= 2;
}
unset($num); // always unset reference after loop

print_r($numbers); // [2, 4, 6, 8, 10]

Note: Always call unset() on the reference variable after a reference-based foreach. Failing to do so can cause subtle bugs when the variable is reused later in the same scope.

-Tip-