Array Loops (Foreach)

There will be times when you want to perform an action for each value in an array. With PHP, there is an easy way to do this, and we gave it away in the last sentence.

The foreach loop is a variation of the for loop, but it only works with arrays. It will loop through an entire array, performing the specified actions for each value in the array.

As a simple example of the foreach loop, we will create an array and loop through it to echo each separate value:

<?php
  $characters[0] = "Bugs Bunny";
  $characters[1] = "Tweety";
  $characters[2] = "Wile E. Coyote";
  $characters[3] = "Elmer Fud";
  $characters[4] = "Sylvester";
  $characters[5] = "Road Runner";

  foreach ($characters as $value) {
    echo $value . "<br />";
  }
?>

When the foreach loop first begins, the first value in the $characters array is stored in the $value variable. That value can be referenced throughout the remainder of that first loop, but will be replaced with the array's next value when the next loop begins. The foreach loop will continue looping until the array runs out of values.

This simple example works with the values of both numerical and associative arrays, but does not work with the keys. In order to work with the keys of both numerical and associative arrays, the "=>" combination must once again be added to the mix.

<?php
  $characters['pig'] = "Porky Pig";
  $characters['duck'] = "Daffy Duck";
  $characters['mouse'] = "Speedy Gonzales";

  foreach ($characters as $key => $value) {
    echo $value . " is a " . $key . ".<br />";
  }
?>

And the result is:

Porky Pig is a pig.
Daffy Duck is a duck.
Speedy Gonzales is a mouse.

Note: The variable names in a foreach loop do not have to be "key" and "value" as long as they follow the standard variable naming rules.