PHP - foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax
foreach ($array as $value) {
//code to be executed
}
There is one more syntax of foreach loop.
Syntax
foreach ($array as $key => $element) {
//code to be executed
}
Example
PHP program to print array elements using foreach loop.
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");
//access array elements using foreach loop
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>