PHP - Foreach Loop


Advertisements

Previous Page Next Page

The PHP foreach loop is used to loop through the key/value pair in a 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;
} 

Foreach loop used with an Array

In the below example, 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"; 
   }
?>

Output

1
2
3
4
5

Foreach loop used with an Associative Array

In the below example, 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"; 
   }
?>

Output

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

Previous Page Next Page
Advertisements