The third loop type is foreach, which is specifically for arrays and objects,
although it is rarely used for anything other than arrays. A foreach loop
iterates through each element in an array (or each variable in an object),
optionally providing both the key name and the value.
In its simplest form, a foreach loop looks like this:
Click here to view code image
<?php
foreach($myarr as $value) {
echo $value;
}
?>
This loops through the $myarr array you created earlier, placing each value
in the $value variable. You can modify it so you get the keys as well as the
values from the array, like this:
Click here to view code image
<?php
foreach($myarr as $key => $value) {
echo "$key is set to $value\n";
}
?>
As you can guess, this time the array keys go in $key, and the array values
go in $value. One important characteristic of the foreach loop is that it
goes from the start of the array to the end and then stops—and by start we
mean the first item to be added rather than the lowest index number. This
script shows this behavior:
Click here to view code image
<?php
$array = array(6 => "Hello", 4 => "World",
2 => "Wom", 0 => "Bat");
foreach($array as $key => $value) {
echo "$key is set to $value\n";
}
?>
If you try this script, you will see that foreach prints the array in the
original order of 6 , 4 , 2 , 0 rather than the numerical order of 0 , 2 , 4 , 6.
The do...while loop works like the while loop, with the exception that
the condition appears at the end of the code block. This small syntactical
difference means a lot, though, because a do...while loop is always executed
at least once. Consider this script: