PHP foreach Loop – A Comprehensive Guide

In this article, we’ll explore how PHP foreach loop works and how it can be used in production environment.

With PHP foreach loop, You can easily iterate over arrays and other iterable data structures.

This loop automatically assigns the key and value of each array element to loop variables, making accessing and manipulating array data easy.

It helps you quickly and easily process your data, whether you’re working with a simple array or a multidimensional array.



PHP foreach Loop

With the use of the foreach loop, each key/value pair in an array is looped through one by one.

It is an ideal choice to use a foreach loop when you don’t know the exact number of elements in an array or object in advance.

Syntax

foreach ($array as $value)
{
//The code that needs to be executed
}

In each iteration of the loop, the current array element’s value is assigned to the variable $value, then the pointer to the next array element is moved by one, until the array reaches the end of the array.

Below is an example that outputs the contents of the array ($flower):

Example: 

<?php $flower = array("sunflower", "rose", "tulip", "jasmine"); foreach ($flower as $value) { echo "$value <br>"; } ?>
Php Foreach Looping
Here is an example that will output both the key and value of the array ($physics_marks):

Example: 

<?php $physics_marks = array("John"=>"85", "Adrian"=>"68", "Daniel"=>"80", "Jennifer"=>"78"); foreach($physics_marks as $a => $value) { echo "$a = $value <br>"; } ?>
Here is an another example that will output both the key and value of the array ($salary):

Example: 

<?php $salary=array("Henry"=>"450000","Rachel"=>"300000","Louis"=>"200000"); foreach($salary as $a => $value) { echo "$a = $value <br>"; } ?>

Example Explanation

Above examples code defines an associative array called $salary, which contains the salaries of three individuals – Henry, Rachel, and Louis.

The keys of the array are the names of the individuals, and the values are their respective salaries.

Then we have used a foreach loop to iterate through the array. In each iteration of the loop, the key of the current array element is assigned to the loop variable $a, and the value of the current array element is assigned to the loop variable $value.

Inside the loop, the code prints the name of the individual (stored in $a), followed by their salary (stored in $value), and a line break (<br>). The output of this code would be a list of the names and salaries of each individual in the $salary array.

Our upcoming article on PHP Arrays will give you a better understanding of arrays.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *