Account
Categories

For Each Loop


It works only on the values of an array.

When it runs, it accesses each value of the array one by one and checks line by line.

The loop automatically exits after checking all elements.

But if you want to exit from the loop in the middle, you can use the break statement, which makes the loop stop right there.

Syntax:

1. Simple foreach (only values):

foreach ($array as $value) {
    // code to run for each element
}
$array → This is the array that the loop will go through
$value → This is the current element value of the array that we use in the loop

2. Foreach with key and value:

foreach ($array as $key => $value) {
    // code to run for each key and value
}
$key → This is the index or key of the array
$value → This is the current element value linked with that key
Example:
<?php
$colors = ["Red", "Blue", "Green", "Yellow"];

// you want to find the color "Green"
foreach ($colors as $color) {
    if ($color == "Green") {
        echo "Your favorite color is $color!<br>";
    } else {
        echo "$color is not your favorite.<br>";
    }
}
?>
Output:
Red is not your favorite.
Blue is not your favorite.
Your favorite color is Green!
Yellow is not your favorite.