PHP Foreach Loop – Work With Various Types of Arrays

What is PHP Foreach Loop

PHP Foreach loop is used on arrays elements to loop through each pair of values of an array. The loop traverses through each item of an array and assigns each item to a variable(e.g. $item).

This loop works only with arrays elements. The number of iteration perform by PHP foreach loop to traverse through each element depends upon the number of items present in an array. If the array contains two items, two iterations will be performed by the loop and the pointer will move to the next element if exists.

You can print the assigned values one by one using the PHP echo statement. Checkout the below-given examples to learn how to work with array using PHP foreach loop.

PHP Foreach Syntax

The syntax contains the two variables(e.g. $array and $item). $array contains the array to which you want to perform foreach loop and $item is the variable to which you assign and print each item.

Here, In the syntax, the array can be Indexed, Associative. You can iterate through the Multi-dimensional array but you need extra for loop to break down each item of arrays.

Example of PHP Foreach loop

Example 1: Foreach loop for Indexed Array

The example shows the Foreach loop to iterate through the Indexed Array type. The indexed array is the simple array type with no keys for values.

Output

Sachin
Virat
Dhoni

Example 2: Foreach loop for Associative Array

The example shows the foreach loop to iterate through the Associative array type. The associative array contains the pair of items with keys elements to identify or relate each item with keys.

Output

Rohit scored 264 runs
Sachin scored 200 runs
Virat scored 186 runs