Skip to main content

PHP Foreach Loop With Examples – PHP Loop Tutorial

Foreach is one of the advance loop feature provided by PHP. In this tutorial, we will explore in-depth of PHP foreach loop.

You should have the basic understanding of PHP to understand this chapter. Before reading this tutorial you should read the following topic in a little bit deeper.

  1. PHP Array
  2. Class and Object in PHP

foreach in php loop

The Foreach loop is just another type of advance loop in PHP which we can use with array and object datatype. PHP internally manage the increment counter and initialization in foreach loop so you do not need to take help of initialization and increment like For Loop. If it is used to iterate other than object and array then it will throw an error.

Foreach supports following two type of syntax:

foreach(array_expression/object as value)
statement;

And

foreach(array_expression/object as  key => value)
statement;

Like other PHP loop construct, we can add multiple lines of the statement in foreach by clubbing the statement in curly braces.

foreach(array_expression/object as  key => value){
statement1;
statement2;
statement3;
}

For the better readability, we should always use curly braces with foreach. So that if you or someone else will debug your code after some time it will be readable. 

Following is a basic foreach example
$names = array('Ankur', 'John', 'Joy');
foreach ($names as $name) { //foreach loop of name array
print $name . ' ';
}

The above code will print “Ankur John Joy” on the screen.

Now the same example with key value in foreach.
$names = array('Ankur', 'John', 'Joy');
foreach ($names as $key => $value) { //foreach with key value
print $key . '=>' . $value . ',';
}

The above code will print 0=>Ankur,1=>John,2=>Joy, on the screen.

So in the PHP Foreach to iterate we do not need any counter for initialization, increment and condition checking. It will iterate through ever element of collection internally and provide you the collection values for operation.

Below is a flowchart of PHP Foreach loop.
PHP Foreach

In above flowchart, you can see that the Foreach construct check the array or object expression for its count.

PHP Foreach Loop With Key and Value

You can both key and value of the array by the foreach loop. You need to pass $key => $value both in the second part of the foreach construct.

$array = array(2, 4, 6, 8);
foreach ($array as $key => $value) {
echo 'key is' . $key . ' & value is' . $value."\n";
}

It will print output:

key is0 & value is2
key is1 & value is4
key is2 & value is6
key is3 & value is8

Above example is printing key of the array which is 0,1,2,3.

You can also use the foreach loop to iterate through the unsequential and non-integer key value pair like below:
$array_complex = array(0=>'Ankur', 'fruit'=>'Orange', '5'=>'test', '9'=>'test2');
foreach ($array_complex as $key => $value) {
echo 'key is ' . $key . ' & value is ' . $value."\n";
}

The output of the above will:

key is 0 & value is Ankur
key is fruit & value is Orange
key is 5 & value is test
key is 9 & value is test2

PHP Foreach loop by colon syntax

PHP Foreach loop also supports the colon syntax.

foreach($array as key =>value):
statement;
endforeach;

Below is the simple example:
$data_names = array('Ankur', 'John', 'Joe');
foreach ($data_names as $key => $value):
echo 'key is ' . $key . ' & value is ' . $value."\n";
endforeach;

Normally we use the colon syntax foreach in HTML. Let us suppose there is an array contains country names. Now you want to list the country as ordered list into your page then you can use the colon syntax in foreach like below.

<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ol>
<?php
$countries = array('India', 'USA', 'UK', 'France', 'Italy');
foreach ($countries as $country):
?>
<li><?php print $country ?></li>
<?php
endforeach;
?>
</ol>
</body>
</html>

Above Code will print order list of country like below.
PHP Foreach Colon

Nested Foreach and Multidimensional Array

We can use the nested foreach. Normally we used the nested foreach for operation on a multidimensional array. But nested foreach is not limited to used with multidimensional array only. Multidimensional Array and nested foreach:
$list_array = array( 1 => array('id' => '1010', 'name' => 'Ankur'), 2 => array('id' => '1020', 'name' => 'John'), 5 => array('id' => '1080', 'name' => 'Joe'), 9 => array('id' => '1007', 'name' => 'Test'), );
foreach ($list_array as $array) {
foreach ($array as $key => $value) {
print 'Key=>' . $key . ' value=>' . $value . "\n";
} print "\n";
}

Below is the output of above code.
Nested Foreach
So to operate on associative array we can use the nested foreach if required.

Foreach With PHP Objects

Foreach also works with object data type in PHP. It works on both stdClass objects as well as the normal PHP class object. In both stdClass and normal class objects, it iterates on the property of the object. In the normal class object, the foreach behavior works along with the visibility. If you will use foreach inside the class it will iterate to the public, private and protected properties. But if you will use foreach outside the class then it will iterate through only public properties. Standard Object with Foreach: $obj_standard = new stdClass(); $obj_standard->id = 1; $obj_standard->name = 'Ankur'; $obj_standard->country = 'India'; foreach ($obj_standard as $key => $value) { print $key . '=>' . $value . "\n"; } Output of the above code will be:

id=>1
name=>Ankur
country=>India

Normal PHP Class Object and Foreach:
As you know that the foreach will print all accessible property according to the context of the use of the foreach. Let us see the below example:
class test {
var $id;
var $name = 'Ankur';
var $country = 'India';
protected $phone = '12121';
private $email = 'test[at]test';
public function __construct($id) {
$this->id = $id;
}
public function inside_foreach() {
foreach ($this as $key => $value) {
print $key . '=>' . $value . "\n";
}
}
}
$obj_test = new test(3);
print "Outside View \n";
foreach ($obj_test as $key => $value) {
print $key . '=>' . $value . "\n";
}
print "Inside of The Class View \n";
$obj_test->inside_foreach();

The above code will give the following output:

Outside View 
id=>3
name=>Ankur
country=>India
Inside of The Class View 
id=>3
name=>Ankur
country=>India
phone=>12121
email=>test[at]test

Let us evaluate the reason. So the first foreach after the creation of an object of the class will not have private and protected properties because it is an object of the test class. However $this will always have all i.e. private, protected and public properties access.

We can use the mix of the array, object, single dimension, multidimensional and associative array together with the foreach.

Foreach and List in PHP

From PHP version 5.5.0 we can use list function into the foreach to iterate in the multidimensional array with unpacking the nodes. It helps to minimize the number of foreach nesting and make our code simplified.

Now let us consider the following array.
$mextrix = array(array(1,2),array(3,4),array(5,6));
Not to go till last node value i.e. 1,2,3,4 via foreach either we need to use two loops or after one loop we need to call array element directly like $value[1] or $value[2]. But from PHP 5.5.0 onwards we can use PHP list function inside the foreach loop like below:
$mextrix = array(array(1, 2), array(3, 4), array(5, 6));
foreach ($mextrix as list($a, $b)) {
print $a . ',' . $b . PHP_EOL;
}

The above code will produce the following output:

1,2
3,4
5,6

Because we have used list function with $a and $b.

List can be used to print one out of many in either way like
$mextrix = array(array(1, 2), array(3, 4), array(5, 6));
foreach ($mextrix as list($a)) {
print $a;//will print 1,3,5
}
foreach ($mextrix as list(,$a)) {
print $a;//will print 2,4,6
}

Foreach Pass by value or reference

Foreach works as pass by value methodology however you can pass the value as by reference using &value in the foreach function.

$test_foreach_array = array(2,4,6,8);
foreach($test_foreach_array as $value){
$value = $value+5;
}
print_r($test_foreach_array);//will print Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
foreach($test_foreach_array as &$value){
$value = $value+5;
}
print_r($test_foreach_array);// Will Print Array ( [0] => 7 [1] => 9 [2] => 11 [3] => 13 )

Now let us take a surprising example:
$names = array('Ankur', 'Joe', 'Ajay');
foreach($names as &$value){
//Do Nothing
}
foreach($names as $value){
print $value;
}

Can you guess what will be the output of above code from print?

It should be AnkurJoeAjay, but it will be Ankur, Joe, Joe.

Is it a bug in foreach process?

Not it is not. It is behavior. Now let us dry run the program.
If you will print $value just after the first loop which is foreach($names as &$value) then you will get Ajay in it. So $value is still referencing $names[2]. So even if you will write $value = ‘ABC’ and then print the array $names then the last element which is $names[2] will be replaced by ABC and this is the catch.

Now, let us clearly evaluate the second loop which is still a point of reference for the $names. Now let us dry run the loop.

  1. First time $names[2] and $value will be $names[0] and will print Ankur. Because always $value is point of reference for $name[2].
  2. Second Time $names[2] and $value will be $names[1] and the value will be Joe. Now be careful as the last time $names[2] is replaced by $names[1]. So finally at this stage, $names[2] will have value Joe
  3. Third time $name[2] is already replaced by $names[2], so third or last time again Joe will be printed.

The solution: Unset the $value just after the first loop like below.

foreach($names as &$value){
//Do Nothing
}
unset($value);
foreach($names as $value ){
print $value;
}

Now the behavior will be normal and print will print all element of $names.

Break and Continue in Foreach

We can break the foreach loop using PHP Break keyword and bypass an iteration of the foreach loop by continue using continue keyword.

For example:
$array = array(1,45,33,'stop',3,5);
foreach($array as $val) {
if($val == 'stop'){
break;//Loop will be breaked
}
print $val.',';
}

Above program will print 1,45,33

Similarly, we can use continue keyword as well to skip the loop.
Download Code Used in Tutorial

Next >> PHP While Loop

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

One thought to “PHP Foreach Loop With Examples – PHP Loop Tutorial”

  1. Helpful blog to everyone.. All loop concept explanation are very clear so easy to understand.. thank you for sharing

Leave a comment/Ask Question

shares