PHP - Statement Foreach loop


foreach loop is exclusive for arrays.

It allows you to iterate an array entirely, even if you do not know its keys.

There are two options for the syntax:


     $names = ['A', 'B', 'C']; 
     //option 1//from   w  w  w. j a va  2  s.  com
     foreach ($names as $name) { 
         echo $name . " "; 
     //option 2
     foreach ($names as $key => $name) { 
         echo $key . " -> " . $name . " "; 


The foreach loop accepts an array and it specifies a variable which will contain the value of the entry of the array.

We do not need to specify any end condition.

Optionally, you can specify a variable that contains the key of each iteration, as in the second loop.

Related Topics