In this PHP tutorial, you shall learn about foreach statement, its syntax, and how to use foreach statement to iterate over elements of a collection, example programs.
PHP foreach
PHP foreach looping statement executes a block of statements once for each of the element in the iterable (or iterable expression).
The iterable expression could be an array, or an Iterable.
Syntax
The syntax of foreach statement is
foreach (iterable_expression as $element) {
statement(s)
}
The above syntax can be read as “for each element in the iterable_expression accessed as $element, execute statement(s)“.
During each iteration of the foreach loop, you can access this element of the iterable for that iteration, via $element variable. You may change the variable name as it is developer’s choice.
For associative arrays where elements are key-value pairs, the syntax of foreach statement is
foreach ($array as $key=>$value) {
statement(s)
}
You can access the key and value during each iteration using the variables $key and $value.
Examples (3)
1. foreach with Array
In this example, we will take an indexed array of elements, iterate over each of the elements in the array, and execute a block of code (or statements) for each element.
Inside foreach block, we will print square of the element.
PHP Program
<?php
$array = [2, 5, 3, 7, 1, 8];
foreach ( $array as $element ) {
echo $element * $element;
echo "<br>";
}
?>
Output
