PHP Tutorial PHP Advanced PHP References

PHP - Foreach Loop



The PHP foreach loop is used to loop through each element of an array. In each iteration of the loop, current array element is assigned to a user-defined variable and array pointer is moved by one and in the next iteration next array element will be processed.

Syntax

foreach($array as $variable){
  statements;
} 

Flow Diagram:

PHP Foreach Loop

Foreach loop used with an Array

In the example below, the foreach loop is used on array called numbers which is further used to print each element of the array in each iteration.

<?php
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $x) {
  echo $x."\n"; 
}
?>

The output of the above code will be:

1
2
3
4
5

Foreach loop used with an Associative Array

The foreach loop can be used with an associative array in the same way. It iterates through each key-value pair of the associative array.

In the example below, the foreach loop is used on associative array called info which contains name and age of persons. In each iteration, the foreach loop is used to print these informations.

<?php
$info = array("John"=>"25", "Mary"=>"28", "Kim"=>"32");
foreach ($info as $name => $age) {
  echo "$name is $age years old.\n"; 
}
?>

The output of the above code will be:

John is 25 years old.
Mary is 28 years old.
Kim is 32 years old.