How to Implement foreach loop in PHP with Examples

Published on Sep 09,2019 3.7K Views

How to Implement foreach loop in PHP with Examples

edureka.co

Control Structures are one of the most important aspects of any language and it’s true for PHP too. In this article, we are going to discuss one of the control structure. i.e foreach loop. The Following pointer will be covered in this foreach loop in PHP article:

Table of Content

When we talk about foreach loop, it is a little bit different than the rest of the loops because foreach loop deals with only arrays and objects. It is the best way to access each key/value pair from an array.

 

Moving on with this article on foreach loop in php

Foreach loop in PHP

We use foreach loop mainly for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to value, and the array pointer is advanced by one to go the next element in the array. Though foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time when compared to for loop. It allocates temporary memory for index iterations which makes the overall system to redundant its performance in terms of memory allocation. There are 2 syntaxes followed by foreach loop:

foreach ($array as $value)
{
}   
Foreach ($array as $key => $value)
{
}

In the first form, On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one.

In the second form,$array is an associative array and $key is our array key which we can store inside of a key variable and $value stores the array keys value.

Below example demonstrates the first form of syntax, which we have discussed above

<?php $array = array( "ashok", "tarun", "charan" ); 
foreach( $array as $value )
 { echo $value . "
";
 } 
?> 

 

Second Form

Below example demonstrates the second form of syntax, which we have discussed above

<?php $student = array ( "name" => "ashok", 
"email" => "ashok@mail.com", 
"reg" => 11603529, 
"gender" => "male"
); 
foreach($student as $key => $value) 
{ 
echo $key.": " .$value."
"; 
} 
?> 

With this, we come to an end of this foreach loop in PHP article. I hope you have learned about bout one of the control structure. i.e foreach loop in PHP with the help of few examples.

Check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”Foreach Loop in PHP” and I will get back to you.

BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework