Thursday, October 16, 2025
HomeLanguagesPHP | foreach Loop

PHP | foreach Loop

The foreach construct provides the easiest way to iterate the array elements. It works on array and objects both. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively. It allocates temporary memory for index iterations which makes the overall system to redundant its performance in terms of memory allocation.

Syntax:

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

or

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

Below programs illustrate the foreach loop in PHP:

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




<?php
  
// Declare an array
$arr = array("green", "blue", "pink", "white"); 
  
// Loop through the array elements
foreach ($arr as $element) {
    echo "$element ";
}
  
?>


Output:

green blue pink white

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




<?php 
$employee = array( 
    "name" => "Robert", 
    "email" => "robert112233@mail.com", 
    "age" => 18, 
    "gender" => "male"
  
); 
  
// Loop through employee array 
foreach($employee as $key => $element) { 
    echo $key . ": " . $element . "<br>"; 
} 
  
?> 


Output:

name: Robert
email: robert112233@mail.com
age: 18
gender: male
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS