The foreach construct is a variation of the for loop and is used to iterate over arrays. There are two different versions of the foreach loop.
The basic foreach loop syntaxes are shown below:
foreach (array as $value)
{
statement
}
foreach (array as $key => $value)
{
statement
}
The first type of foreach loop is used to loop over an array denoted byarray. During each iteration through the loop, the current value of the array is assigned to the variable - $value and the loop counter is incremented by a value of one. Looping continues until the foreach loop reaches the last element or upper bound of the given array. During each loop, the value of the variable - $value can be manipulated but the original value of the array remains the same. To change the actual value of the array, it is necessary to replace the "$" symbol with the "&" symbol. Any changes made to &value, can be assigned to the array element at the current index.
The following example demonstrates how the foreach loop is used to interate over the values of an array:
<?php
$my_array = array('red','green','blue');
echo "The different colors include: ";
foreach($my_array as $value)
{
$colors .= $value . " ";
}
echo $colors;
?>
During each loop, the color name associated with the current array element is assigned to a variable - $colors. A single space " " is also added between each of the color names for display purposes. When the loop reaches the end of the array, the output below is generated:
The different colors include: red green blue
The second form of the loop provides the same functionality as the first, but also assigns the current array element's index or key to be assigned to the variable - $key on each loop. In the previous example, the array $my_array contains three elements: $my_array[0] = "red", $my_array[1] = "green", and $my_array[2] = "blue". While the variable - $value contains the array element values: red, green, and blue, the variable $key contains the array element indices: 0, 1, and 2.