PHP foreach

Created with Sketch.

PHP foreach

Summary: in this tutorial, you will learn how to use PHP foreach statement to loop over elements of an array.

Introduction to the PHP foreach statement

PHP provides you with the foreach statement that allows you to iterate over elements of an array, either an indexed array or an associative array.

The foreach statement iterates over all elements in an array, one at a time. It starts with the first element and ends with the last one. Therefore, you don’t need to know the number of elements in an array upfront.

The following flowchart illustrates how the foreach statement works:

PHP foreach

PHP foreach with indexed arrays

To iterate over all elements of an indexed array, you use the following syntax:

<?php

foreach ($array_name as $element) {
// process element here
}

Code language: HTML, XML (xml)

When PHP encounters a foreach statement, it assigns the first element of the array to the variable following the as keyword ($element).

In each iteration, PHP assigns the next array element to the $element variable. If PHP reaches the last element, the loop ends.

The following example uses the foreach statement to display elements of the $colors array:

<?php

$colors = ['red', 'green', 'blue'];

foreach ($colors as $color) {
echo $color . '<br>';
}

Code language: HTML, XML (xml)

Output:

red
green
blue

Code language: plaintext (plaintext)

PHP foreach with an associative array

To iterate over elements of an associative array, you use the following syntax:

<?php
foreach ($array_name as $key => $value) {
//process element here;
}

Code language: HTML, XML (xml)

When PHP encounters the foreach statement, it accesses the first element and assigns:

  • The key of the element to the $key variable.
  • The value of the element to the $value variable.

In each iteration, PHP assigns the key and value of the next element to the variables ($key and $value) that follows the as keyword. If the last element is reached, PHP ends the loop.

The following example illustrates how to use the foreach statement to iterate over elements of the captials array:

<?php

$capitals = [
'Japan' => 'Tokyo',
'France' => 'Paris',
'Germany' => 'Berlin',
'United Kingdom' => 'London',
'United States' => 'Washington D.C.'
];

foreach ($capitals as $country => $capital) {
echo "The capital city of {$country} is $capital" . '<br>';
}

Code language: HTML, XML (xml)

Output:

The capital city of Japan is Tokyo
The capital city of France is Paris
The capital city of Germany is Berlin
The capital city of United Kingdom is London
The capital city of United States is Washington D.C.

Code language: plaintext (plaintext)

Summary

  • Use the foreach($array_name as $element) to iterate over elements of an indexed array.
  • Use the foreach($array_name as $key => $value) to iterate over elements of an associative array.

Leave a Reply

Your email address will not be published. Required fields are marked *