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
$arr = array("green", "blue", "pink", "white");
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"
);
foreach($employee as $key => $element) {
echo $key . ": " . $element . "<br>";
}
?>
|
Output:
name: Robert
email: robert112233@mail.com
age: 18
gender: male
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
25 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...