The foreach Loop in PHP
The foreach loop is used to iterate
through all elements of an array.
Let an array be given. Let's output all its elements to the screen as an example:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
}
?>
Code execution result:
12345
The syntax is as follows: the name of the array being
iterated, then the keyword as,
then the name of the variable into which the array elements
will be sequentially placed. In our
case, its name is $elem, but we can
give it any name.
The foreach Loop and an Associative Array
This loop can also be used to iterate through the elements of an associative array in PHP:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
foreach ($arr as $key => $elem) {
echo $key . '-' . $elem; // will output: 'a-1', 'b-2', 'c-3' and so on...
}
?>
In this case, the keys of our array will be placed
into the variable $key,
and the value into
$elem. The variable does not necessarily have to be
named $key, the name can be any.
See Also
-
lesson
the foreach loop in PHP -
lesson
the while loop in PHP -
lesson
the for loop in PHP