The foreach statement is a special looping facility to iterate over array elements. The syntax of a foreach statement is as given below.
foreach (array as value)
statement;
This will become more clear by examples. Example: Suppose that we have an array of five integers. We want to multiply each of these elements by 4. We can do so by using a while loop as below.
$array = array(1,2,3,4,5);
$i=0;
while(i<5){
$array($i) = $array($i) * 4;
}
We can do the same thing by using the foreach loop as below.
$array = array(1,2,3,4,5);
foreach($array as $value)
$value = $value * 4;
Notice that here $value acts as the array element at any iteration. Not the value only. Because the changes to this $value are being stored as the changes in the array elements.
Due to this we need to unset the reference to the last array element after the loop if we do not wish to let the reference remain. We do so by using the unset() function. This function breaks the refernce of the variable $value with the array $array element. Note that if you come out of the loop using some break statement, then also the $value will have the reference to the last accessed array element. unset($value) destroys all such references.
We can also access each of the array elements of an associative array with their respective key ids as below.
$array = array("name","age"=>"john","23");
foreach($array as $key => $value)
{
echo $key;
echo $value;
}