PHP Foreach Loop

The foreach loop is used to execute a block of code for each element in an array.

Syntax

foreach ($array as $value) {
    // code to be executed
}

Example of PHP Foreach Loop

<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
    echo "$color\n";
}
?>

Output:

red
green
blue

Explanation: This example demonstrates the use of the foreach loop in PHP. The loop executes 3 times, and the value of each element in the $colors array is printed each time.