[Previous] [Contents] [Next]


foreach


The foreach statement was introduced in PHP4 and provides a convenient way to iterate through the values of an array. Like a for loop, the foreach statement executes the loop body once for each value in an array. The following code fragment converts an array of centimeter values to inches for each value in the array:

// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);

// Convert an array of centimeter lengths to inches
foreach($lengths as $cm)
{
  $inch = (100 * $cm) / 2.45;
  echo "$cm centimeters = $inch inches\n";
}

The foreach loop is an extremely useful and convenient method of processing arrays and is discussed in detail in Section 2.5.2.


[Previous] [Contents] [Next]