PHP foreach Loop

Unlike other loops, the foreach loop in PHP works only for arrays. The foreach loop is used when we need execute some block of codes, multiple times, for each element of an array. For example:

   $languages = array("Python", "CSS", "JS", "PHP", "SQL");
   foreach($languages as $x)
      echo $x;
      echo "<BR>";

The output of above PHP example, is shown in the snapshot given below:

php foreach loop

PHP foreach Loop Syntax

The syntax of foreach loop in PHP, is:

foreach($array as $value)
   block of code;

For the first time, the first element of the array gets assigned to $value. Similarly at second time, the second element of the array gets assigned to $value, and so on. This process continues, until the last element.

PHP foreach Loop Example

This example uses an array whose elements are in key-value pairs.

   $addr = array("Name"=>"Lucas", "Age"=>"26", "City"=>"Frankfurt");
   foreach($addr as $k => $v)
      echo "$k = $v <BR>";

The snapshot given below shows the sample output produced by this PHP example, on foreach loop:

foreach loop in PHP

PHP Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube