PHP Manual
Prev | Chapter 11. Control Structures | Next

# `foreach`

PHP4 (not PHP3) includes a `foreach` construct, much like perl and some other languages. This simply gives an easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first:

      1
      2 foreach(array_expression as $value) statement
      3 foreach(array_expression as $key => $value) statement
      4

The first form loops over the array given by `array_expression`. On each loop, the value of the current element is assigned to `$value` and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable `$key` on each loop.

When `foreach` first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a `foreach` loop.

You may have noticed that the following are functionally identical:

      1
      2 reset ($arr);
      3 while (list(, $value) = each ($arr)) {
      4     echo "Value: $value<br>\n";
      5 }
      6
      7 foreach ($arr as $value) {
      8     echo "Value: $value<br>\n";
      9 }
     10

The following are also functionally identical:

      1
      2 reset ($arr);
      3 while (list($key, $value) = each ($arr)) {
      4     echo "Key: $key; Value: $value<br>\n";
      5 }
      6
      7 foreach ($arr as $key => $value) {
      8     echo "Key: $key; Value: $value<br>\n";
      9 }
     10

Some more examples to demonstrate usages:

      1
      2 /* foreach example 1: value only */
      3
      4 $a = array (1, 2, 3, 17);
      5
      6 foreach ($a as $v) {
      7    print "Current value of \$a: $v.\n";
      8 }
      9
     10 /* foreach example 2: value (with key printed for illustration) */
     11
     12 $a = array (1, 2, 3, 17);
     13
     14 $i = 0; /* for illustrative purposes only */
     15
     16 foreach($a as $v) {
     17     print "\$a[$i] => $k.\n";
     18 }
     19
     20 /* foreach example 3: key and value */
     21
     22 $a = array (
     23     "one" => 1,
     24     "two" => 2,
     25     "three" => 3,
     26     "seventeen" => 17
     27 );
     28
     29 foreach($a as $k => $v) {
     30     print "\$a[$k] => $v.\n";
     31 }
     32

Prev | Home | Next
`for` | Up | `break`