php

Use of Foreach Loop in PHP

Different types of loops can be used in PHP. The foreach loop is one of them. This loop is used primarily to parse array and object variables. When the total number of iterations of the loop is not defined, it is better to use a foreach loop than another loop. The number of iterations of this loop will depend on the number of array elements or the number of properties of the object used in the loop for reading values. How this loop can be used for reading array and object variables has been shown in this tutorial.

Syntax:

The foreach loop can be used to read the array values only or read both keys and values of the array.

The following foreach loop is used for reading the element values of an array. It can be used to read both numeric and associative arrays. Each element value of the array will be stored in a variable in each iteration.

foreach ($array as $value) {

    //statements
}

The following foreach loop is used for reading the element values of an array. It is mainly used to read associative arrays. In each iteration of the loop, each key and value of the array will be stored in two variables.

foreach ($array as $key => $element) {

    //statements
}

Example-1: Reading a numeric array

The following example shows how to read the numeric array using the foreach loop. Create a PHP file with the following script. A numeric array named $num_array of 10 elements has been declared in the script, and an empty array named $new_array has been declared to store the even numbers from the numeric array. The foreach loop has been used to iterate the numeric array, and the ‘if’ statement has been used to find out the even numbers from the $num_array and stored all even numbers into the $new_array. Another foreach loop has been used to print the values of $num_array.

<?php
//Declare a numeric array
$num_array = array(12, 90, 15, 6, 32, 38, 75, 57, 60, 78);

//Declare an empty array
$new_array = array();

//initialize the index for the empty array
$index = 0;

echo "The array values are : <br/>";

/* Iterate the numeric array to find out the numbers divisible by 5 and store in a new array */

foreach ($num_array as $value) {
 if ($value%5 == 0)
 {
    $new_array[$index] = $value;
    $index++;
  }
  echo $value." ";
}

echo "<br/><br/>The list of numbers which are divisible by 5 : <br/>";

//Print the values of the $new_array array
foreach ($new_array as $value) {

    echo $value." ";
}

?>

Output:

The following output will appear after running the script from the server. The output shows that there are four even numbers in the numeric array.

Example-2: Reading an associative array

The following example shows how to read an associative array and store the particular keys from the array to another array using a foreach loop. Here, the associative array named $members contains the member’s name as key and Present or Absent as the value of the array. An empty array named $present_member has been used to store the names of the present members. Next, the foreach loop has been used to print the values of $present_member.

<?php

//Declare an associative array
$members = array('Mehr Nigar' => 'Present', 'Ahmmed Ali' => 'Present', 'Maksudur Rahman' => 'Absent', 'Farzana Akter' => 'Present', 'Kamal Hasan' => 'Absent');

//Declare an empty array
$present_members = array();

//Initialize the index for the array
$index = 0;

//Find out the list of present memebers
foreach ($members as $key => $value) {    
 
   if ($value == 'Present') {
    $present_members[$index] = $key;
    $index++;
   }
}

//Count the total numbers of present members
$count = count($present_members);

echo "<b>$count members are present.</b><br/> <br/>";
echo "<b>The members are : </b><br/>";

//Print the list of present members
foreach ($present_members as $value) {

    echo $value. "<br/>";
}
?>

Output:

The following output will appear after running the script from the server. The associative array contains three Present values and two Absent values. For this, the output shows three names of the member from the $members array who are present.

Example-3: Reading the properties of the object variable


The following example shows how to read the property names and the values of any object. Create a PHP file with the following script. A class named Customer has been defined in the script that contains three public properties with values. Next, the $object variable has been created to access the properties of the class. The object variable can be parsed like the associative array using the foreach loop. The foreach loop has been used here to read the property name and the property value of the object variable, $object. Each property name and value of the $object will be read in each loop iteration and printed in each line.

<?php

//Define the class with three properties
class Customer
{
    public $name = 'Mehnaz Hossain';
    public $email = '[email protected]';
    public $phone = '0184423675';
}

//Create object of the class
$object = new Customer();

//Print the object properties using foreach loop
echo "<h3>The customer details: </h3>";

foreach($object as $property => $value)
{
    echo "$property = $value <br/>";
}
?>

Output:

The following output will appear after running the script from the server. The Customer class contains three properties: name, email, and phone. These properties are initialized with the values inside the class. The property names and values are printed in the output.

Example-4: Reading the values of the dynamic array

Create a PHP file with the following script to know the use of the foreach loop to read the dynamic array’s content. In the following script, a random number between 1 to 10 will be generated using the rand() function. Next, the range() function will create an array of numbers based on the random value, and the foreach loop will be used to print the array values.

<?php
//Initialize a random number
$number = rand(1,10);

//Print the dynamic array values based on random value]
foreach (range(0, $number) as $value)
{
    echo "$value\n";
}

?>

Output:

The following output will appear after executing the above script.

Example-5: Reading the values of two-dimensional numeric array

Create a PHP file with the following script to iterate the values of the two-dimensional numeric array by using the nested foreach loop. A two-dimensional array of 5 rows and 3 columns has been declared in the script. The outer foreach loop has been used to read the row values of the array, and the inner foreach loop has been used to read the column values of the array. Here, <pre> tag has been used to display the output with the tab space.

<?php

 //Declare a two-dimensional numeric array
 $products = array(array('HDD','Samsung', '$50'),
 array('Monitor','DELL', '$90'),
 array('Mouse','A4Tech', '$5'),
 array('Printer','HP', '$120'),
 array('RAM','OCZ', '$40'));
 
 echo "<pre>";
 //Print the heading
 printf("<b>Name\t\tBrand\t\tPrice</b>\n");
 //Print the values of two-dimensional array using nested foreach loops  
 foreach ($products as $item) {
    foreach ($item as $value) {
     //Print the value with the tab space
     printf("%s\t\t", $value);
    }
    echo "<br/>";
 }
 echo "</pre>";

?>

Output:

The following output will appear after executing the above script.

Example-6: Reading the values of multi-dimensional associative array

Create a PHP file with the following script to iterate the values of the two-dimensional associative array by using the nested foreach loop. A two-dimensional array of 4 rows and 4 columns has been declared in the script. The outer foreach loop has been used to read the row values of the array, and the inner foreach loop has been used to read the column values of the array.

<?php

//Declare four one-dimentional array of four elements
$student1 = array("id"=>01, "name"=>"Mir Sabbir", "batch"=>40, "dept"=>'CSE');
$student2 = array("id"=>02, "name"=>"Mahbubur Rahman", "batch"=>45, "dept"=>'BBA');
$student3 = array("id"=>03, "name"=>"Sakil Ahmed", "batch"=>48, "dept"=>'English');
$student4 = array("id"=>04, "name"=>"Ashikur Rahman", "batch"=>51, "dept"=>'ETE');

//Declare two-dimentional array
$mult_array=[$student1, $student2, $student3, $student4];

//Print the keys and values of two-dimentional associative array
foreach ($mult_array as $student){

    foreach ($student as $key=>$value){
        echo "<b> $key </b> : $value <br/>";
    }
    echo "<br/><br/>";
}
?>

Output:

The following output will appear after executing the above script.

Example-7: Terminate the loop based on the specific condition

Create a PHP file with the following script to iterate the values of an associative array using a foreach loop and search a particular key in the array. If no value is provided in the URL, ‘None’ will be set as the search value. If the key exists in the array, then the value of the corresponding key will be printed, and the iteration of the loop will be stopped by using the break statement. A message will be printed if the search key does not exist in the array.

<?php

//Declare an associative array
$flowers = ["Rose"=>90, "Water Lily"=>87, "Lotus"=>45, "Marigold"=>65, "Sunflower"=>60, "jasmine"=>23, "Poppy"=>54];

//Initialize the search value
$search = isset($_GET['name'])?$_GET['name']:'None';
$found = false;

//Read the keys and values of the array using foreach loop
foreach($flowers as $key => $value)
{
    //Exit from the loop if the search value exists in the loop
    if($key == $search)
    {
         echo "Tolal number of $key is $value.";
        $found = true;
        break;
    }
}

//Print the message for unsuccessful search
if($found == false) echo "The search item does not exist."

?>

Output:

The following output will appear after executing the above script.

Example-8: Removing the specific array elements

Create a PHP file with the following script to remove particular array elements from an associative array using a foreach loop. Two arrays have been declared in the script. One is an associative array, and another is a numeric array. The value of the numeric array that matches with the key of the associative array will be removed from the associative array. The associative array values will be printed before and after removing the particular elements. According to the numeric array values, three associative array values will be removed.

<?php
//Declare an associative array
$flowers = ["Rose"=>90, "Water Lily"=>87, "Lotus"=>45, "Marigold"=>65, "Sunflower"=>60, "jasmine"=>23, "Poppy"=>54];

echo "<b>The original array values:</b><br/><pre>";
print_r($flowers);
echo "</pre>";

//Initialize the search value
$search = [ 'Marigold', 'jasmine', 'Poppy' ];

foreach($search as $search_value)
{
    //Read the keys and values of the array using foreach loop
    foreach($flowers as $key => $value)
    {
          //Exit from the loop if the search value exists in the loop
        if($key == $search_value)
        {
            //Remove the value
            unset($flowers[$key]);
        }
    }
}

echo "<br/><b>The array values after remove:</b><br/><pre>";

print_r($flowers);

echo "</pre>";
?>

Output:

The following output will appear after executing the above script.

Conclusion:

The various uses of the foreach loop in PHP have been described in this tutorial using multiple examples. The ways of reading different arrays and object variables using the foreach loop have been shown here. This loop is better when the records are retrieved from any database table using PHP. This loop can be used to read only the array values or property values of the object and read the array values with keys or the property value with the name.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.