Home > Article > Backend Development > PHP foreach loop
PHP foreach loop
foreach loop only works on arrays and is used to iterate over each key/value pair in the array.
Syntax
foreach ($array as $value) {
code to be executed;
}
Every time a loop iteration is performed, the value of the current array element will be assigned to the $value variable, and the array pointer will Move one by one until you reach the last array element.
The following example demonstrates a loop that will output the values of a given array ($colors):
Example
<?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>