PHP For Each
PHP provides
foreach statement to allows you to iterate over an
array easier.
foreach statement only works with
array. If you try to use it with other, the system will issue an error. in PHP 5 you can use
foreach with object too. The syntax of PHP
foreach is very simple as follows:
foreach (array as $value)
statements
// or
foreach (array as $key => $value)
statements
The first form iterate over an array and each element value is assigned to
value in each iteration.
The second form acts similar the the first form except the element key is assigned to the
key in each iteration.
Let's take a look at several example to see how
foreach statement works.
<?php
$a = array(1, 2, 3, 4, 5);
foreach ($a as $val) {
echo $val;
}
?>
In the above example, you first defined an array which contains five elements. Then you use the
foreach statement to loop over that array. In each iteration you printed each element's value to the screen.
$a = array
(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
);
foreach ($a as $key => $val) {
echo "\$a[$key] => $val.\n";
}
In the second example, you use defined an associative array which contains five elements. Then you loop through the array and print out both key and value of each element in each iteration.