Using foreach Loops with Arrays
As we discussed earlier, the easiest way to iterate through-or traverse-an array is using the foreach statement.The foreach statement was specifically introduced in PHP4 to make working with arrays easier.
The foreach statement has two forms:
foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement
Both iterate through an array expression, executing the body of the loop for each element in the array. The first form assigns the value from the element to a variable identified with the as keyword; the second form assigns both the key and the value to a pair of variables.
The following example shows the first form in which the array expression is the variable $lengths, and each value is assigned to the variable $cm:
// 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 = $cm / 2.54;
echo "$cm centimeters = $inch inches\n";
}
The example iterates through the array in the same order it was created:
0 centimeters = 0 inches 107 centimeters = 42.125984251969 inches 202 centimeters = 79.527559055118 inches 400 centimeters = 157.48031496063 inches 475 centimeters = 193.87755102041 inches
The first form of the foreach statement can also iterate through the values of an associative array, however the second form assigns both the key and the value to variables identified as $key => $value. The next example shows how the key is assigned to $animal, and the value is assigned to $sound to generate verses of "Old MacDonald":
// Old MacDonald
$sounds = array("cow"=>"moo", "dog"=>"woof",
"pig"=>"oink", "duck"=>"quack");
foreach ($sounds as $animal => $sound)
{
echo "<p>Old MacDonald had a farm EIEIO";
echo "<br>And on that farm he had a $animal EIEIO";
echo "<br>With a $sound-$sound here";
echo "<br>And a $sound-$sound there";
echo "<br>Here a $sound, there a $sound";
echo "<br>Everywhere a $sound-$sound";
}
This prints a verse for each $animal/$sound pair in the $sounds array:
Old MacDonald had a farm EIEIO And on that farm he had a cow EIEIO With a moo-moo here And a moo-moo there Here a moo, there a moo Everywhere a moo-moo Old MacDonald had a farm EIEIO And on that farm he had a dog EIEIO With a woof-woof here And a woof-woof there Here a woof, there a woof Everywhere a woof-woof
When the second form of the foreach statement is used with a nonassociative array, the index is assigned to the key variable and the value to the value variable. The following example uses the index to number each line of output:
// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);
// Convert an array of centimeter lengths to inches
foreach($lengths as $index => $cm)
{
$inch = $cm / 2.54;
$item = $index + 1;
echo $index + 1 . ". $cm centimeters = $inch inches\n";
}
The foreach statement is used throughout Chapter 4 to Chapter 13.