Foreach Loop

The foreach loop - Loops through a block of code for each element in an array. It works only on arrays, and is used to loop through each key/value pair in an array.

 

Syntax:

foreach( $array as $element ) 
{
    // PHP Code to be executed
}

OR

foreach( $array as $key => $element) 
{
    // PHP Code to be executed
}

 

Example 1: PHP program to print the array elements using foreach loop.

<?php
  
  // Declare an array
  $array = array("black", "blue", "red", "green"); 

  // Loop through the array elements
  foreach ($array as $val) {
      echo "$val <br>";
  }
  
?>

- The following example will output the values of the given array ($array):

 

Output:

black
blue
red
green

 

Example 2: PHP program to print the associative array elements using foreach loop.

<?php 
$customer = array( 
    "name" => "Kailash", 
    "email" => "[email protected]", 
    "age" => 26, 
    "gender" => "male"
  
); 
  
// Loop through employee array 
foreach($customer as $key => $value) 
{ 
    echo $key . ": " . $value. "<br>"; 
} 
  
?> 

-The following example will output both the keys and the values of the given array ($customer):

 

Output:

name: Kailash
email: [email protected]
age: 26
gender: male