Foreach
In PHP, the foreach
loop is used to iterate over arrays and objects. It simplifies the process of iterating through elements of an array or the properties of an object without needing to keep track of iteration indices manually. The syntax for a foreach
loop in PHP is as follows:
foreach ($array as $value) {
// Code to be executed for each element in the array
}
Here, $array
is the array being iterated over, and $value
is a variable that represents the value of the current element in each iteration.
Optionally, you can also include the keys along with the values using the following syntax:
foreach ($array as $key => $value) {
// Code to be executed for each element in the array
}
In this syntax, $key
represents the key of the current element, and $value
represents the value of the current element.
For example:
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color <br>";
}
Output:
red green blue