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
1 2 3 |
foreach($array as $item){ //Put your code here to execute } |
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.
1 2 3 4 |
$array = array("Sachin", "Virat", "Dhoni"); foreach($array as $value){ echo $value."</br>"; } |
Output
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.
1 2 3 4 5 6 7 8 |
$array = [ 'Rohit' => '264', 'Sachin' => '200', 'Virat' => '186' ]; foreach($array as $key => $value){ echo $value."scored ".$key." runs"."</br>"; } |
Output
Sachin scored 200 runs
Virat scored 186 runs