PHP Foreach Loop

••• PHP Foreach Loop

After lerned about the for loop concept In this tutorial, you will learn how to use PHP Foreach Loop statement to loop over elements of an array or public properties of an object.

Introduct of PHP Foreach Loop

The foreach construct provides an easy way to iterate over arrays. PHP Foreach Loop works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntex of PHP Foreach Loop

foreach (array_expression as $value)
foreach (array_expression as $key => $value)

The first form loops over the array given by array_expression.

On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).

The second form will additionally assign the current element’s key to the $key variable on each iteration.

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Example of PHP Foreach Loop

The following example demonstrates a loop that will output the values of the given array ($colors).

PHP assigns each element of the indexed array to the $element variable in each iteration. See the following example:

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
    echo "$value <br>";

You will learn more about arrays in a later tutorial.

Outhput of the above Code


In this tutorial, you have learned how to use the PHP foreach statement to iterate over elements of indexed arrays, associative arrays, and public properties of an object.