PHP Foreach loop

PHP Foreach loop

PHP Foreach loop


The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. Foreach works only on arrays and objects and will issue an error when you try to use it on another type of variable. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as follows:

<?php
  
  foreach (array_variable as variable)
  {
      //code to be executed;
  }
    
  foreach (array_variable as key => variable)
  {
     //code to be executed;
  }
?>

The first form loops over the array are given by array_variable. On each iteration, the value of the current element is assigned to a variable, and the internal array pointer is advanced by one (so in the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

<?php 
   
   $cars = array("BMW", "AUDI", "TOYOTA");
                
  foreach($cars as $car)
  {
     echo $car . " , " ;
  }

  // output  BMW , AUDI ,  TOYOTA ,

?>

Example for the second form

<?php 
   
   $integers = array("one" => 1, "two"=>2, "three"=>3);
                
  foreach($integers as $string => $integer)
  {
     echo $string . " - " . integer . "<br />" ;
  }

  // output
  // one - 1
  // two - 2
  // three - 3

?>

Foreach loop does not operate in the original array and its copy. This means that any changes that are made to the array can not be "seen" from the body of the loop.


Reactions

Post a Comment

0 Comments

close