PHP Foreach

foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects

Below the two syntaxes of foreach loop:

  1. foreach (array_expression as $value)
  2. // statement
  1. foreach (array_expression as $key => $value)
  2. // statement

foreach without key

<?php
 $array = array('One', 'Two', 'Three', 'Four', 'Five');
 foreach ($array as $item) 
   {
     echo "$item<br />";
   }
 ?>

Output:

One
Two
Three
Four
Five

foreach with key and value

<?php
 $array = array('One', 'Two', 'Three', 'Four', 'Five');
 foreach ($array as $key => $item) 
   {
     echo "$key = $item<br/>";
   }
 ?>

Output:

0 = One
1 = Two
2 = Three
3 = Four
4 = Five