PHP Foreach
Whereas a while loop will end should it stumble upon an invalid condition, the foreach loop will process each item in the array using the same operations until it has cycled through each item in the array.
For more PHP loop examples, see:
PHP For Loop
PHP Do While Loop
PHP While Loop
Foreach Syntax
The basic syntax when using a foreach loop is as follows:
foreach (array_expression as $value) statement
The array_expression is the array whose elements we want to process.
The value is the variable we want to assign the element to during each loop.
The statement are the instructions we want to perform during each cycle of the loop.
The foreach loop can be used with an associative array as follows:
foreach (array_expression as $key => $value) statement
All we have done here is add a $key, which is the key assigned to the associative element in the array.
Foreach And An Associative Array
We can use the following example of how to use a foreach loop with an associative array.
Using the same example we had in our array lesson, we have the following:
$color["White"] = 8;
$color["Yellow"] = 2;
$color["Blue"] = 10;
$color["Red"] = 16;
This associative array which specifies how many gallons of paint we have for each color.
Using a foreach loop, we can process each item in the array as follows:
echo “Color: $key, Gallons: $value <br />”;
}
The above example would display:
Color: Black, Gallons: 5
Color: White, Gallons: 8
Color: Yellow, Gallons: 2
Color: Blue, Gallons: 10
Color: Red, Gallons: 16
For more PHP loop examples, see:




