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 "; } ?> |
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>"; } ?> |
name: Robert
email: robert112233@mail.com
age: 18
gender: male
Recommended Posts:
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- How to use for and foreach loop in Golang?
- C# | Using foreach loop in arrays
- How to find the index of foreach loop in PHP ?
- Determine the first and last iteration in a foreach loop in PHP?
- Iterate associative array using foreach loop in PHP
- How to remove an array element in a foreach loop?
- Performance of for vs foreach in PHP
- Node.js | forEach() function
- ES6 | Array forEach() Method
- JavaScript Map forEach() Method
- JavaScript Array forEach() Method
- HTML DOM NodeList.forEach() Method
- AngularJS | angular.forEach() Function
- TypeScript | Array forEach() Method
- HashMap forEach(BiConsumer) method in Java with Examples
- R - while loop
- For loop in R
- JavaScript | While Loop
- while and do while Loop in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

