ptg16476052
Loops 663
24
condition of some kind is satisfied. PHP supports several types of loops: do...while,
while, for, and foreach. I discuss them in reverse order.
foreach Loops
The foreach loop was created for one purpose—to enable you to process all the elements
in an array quickly and easily. The body of the loop is executed once for each item in an
array, which is made available to the body of the loop as a variable specified in the loop
statement. Here’s how it works:
$colors = array('red', 'green', 'blue');
foreach ($colors as $color) {
echo $color. "\n";
}
This loop prints each of the elements in the $colors array with a linefeed after each
color.
Don’t forget that web pages display the line feed as a single
space. If you want them to appear on a new line, you must
include a br tag (for example, echo $color. "<br>\n";).
NOTE
The important part of the example is the foreach statement. It specifies that the array to
iterate over is $colors and that each element should be copied to the variable $color so
that it can be accessed in the body of the loop.
The foreach loop can also process both the keys and the values in an associative array if
you use slightly different syntax. He re’s an example:
$synonyms = array('large' => 'big',
'loud' => 'noisy',
'fast' => 'rapid');
foreach ($synonyms as $key => $value) {
echo "$key is a synonym for $value.\n";
}
As you can see, the foreach loop reuses the same syntax that creates associative arrays.