Foreach Loop in PHP
The foreach loop is used to iterate
through all elements of an array.
The syntax is as follows: the keyword foreach is written,
followed by parentheses ().
These parentheses specify the variable containing
the array to be iterated, then the word as,
and after it - the variable into which, on
each iteration of the loop, an array element
will be placed. Then come the curly braces
{}, which will contain the loop body.
So, the syntax of our loop looks like this:
<?php
foreach ($arrayName as $elementName) {
/*
The code located between the curly
braces will repeat as many times
as there are elements in the array.
*/
}
?>
Let's use the foreach loop to display
all elements of the array on the screen:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
}
?>
Given an array with numbers:
<?php
$arr = [1, 2, 3, 4, 5];
?>
Iterate through this array using a loop and display the squares of these numbers on the screen.
Given an array with numbers:
<?php
$arr = [1, 2, 3, 4, 5];
?>
Using the foreach loop and
the br tag,
display a column of elements from
this array on the screen.