HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Foreach Loop

The foreach loop is specifically for looping through Arrays. It is the most common loop used in modern web development because data from databases and APIs is almost always returned in array format.


Iterating through Values

This is the simplest form of the foreach loop. It loops through every element in the array and assigns the current value to a variable.

<?php
    $colors = array("red", "green", "blue", "yellow");

    foreach ($colors as $value) {
        echo "$value <br>";
    }
?>

Iterating through Keys and Values

For Associative Arrays, you often need both the "Key" (the name/label) and the "Value" (the data). You can access both using the $key => $value syntax.

<?php
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

    foreach($age as $name => $years) {
        echo "$name is $years years old. <br>";
    }
?>
Automatic End: Unlike for or while, you don't need to specify a condition or increment. The loop will automatically stop when it reaches the last element of the array.
Pro Tip: Use foreach whenever you are working with lists of data, such as a list of users, products in a cart, or navigation menu items.

Modifying Array Values

By default, foreach works on a copy of the array. If you want to change the actual values in the original array, you must add an & before the value variable.

<?php
    $nums = [1, 2, 3];
    foreach ($nums as &$val) {
        $val *= 2; // Doubles the original value
    }
    print_r($nums); // Outputs: [2, 4, 6]
?>

Key Points to Remember

  • The foreach loop is built specifically for Arrays and Objects.
  • It doesn't require a counter or a limit—it handles iterations automatically.
  • Use $key => $value to process associative arrays.
  • The loop stops execution when the end of the array is reached.
  • To modify the original array, use the reference operator (&).