Foreach loops in PHP

Foreach loops in PHP can be used to iterate over the contents of an array. They are commonly used for executing the same piece of code multiple times for different data values. There are 2 syntaxes, the first of which iterates over the values, the second iterates over keys and values.

Iterating over values

Each time round the loop, the variable is set to the next value in the array.
<?php

$fruitColours 
= array(
    
"Banana" => "Yellow",
    
"Apple"  => "Green",
    
"Plum"   => "Purple",
);

foreach (
$fruitColours as $colour)
{
    echo 
"$colour<br/>\n";
}

?>

The above will display:

Yellow
Green
Purple

Only the values of the array are displayed.

Iterating over keys and values

Each time round the loop, the variables are set to the next key and value pair.
<?php

$fruitColours 
= array(
    
"Banana" => "Yellow",
    
"Apple"  => "Green",
    
"Plum"   => "Purple",
);

foreach (
$fruitColours as $fruit => $colour)
{
    echo 
"$fruit is $colour<br/>\n";
}

?>

The above will display:

Banana is Yellow
Apple is Green
Plum is Purple

As you can see, in this case both the keys and the values of the array are displayed.