Open In App

How to Use Foreach Loop with Multidimensional Arrays in PHP?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Multi-dimensional array, the task is to loop through array in PHP. The foreach loop is a convenient way to iterate over arrays in PHP, including multidimensional arrays. When dealing with multidimensional arrays, you can use nested foreach loops to access and process each element. In this article, we will explore how to use foreach loops to iterate through multidimensional arrays in PHP.

Basic Syntax of Foreach Loop

The basic syntax of a foreach loop in PHP is as follows:

foreach ($array as $value) {
// Code to be executed for each $value
}

Iterating Through a Multidimensional Array

To iterate through a multidimensional array using foreach loops, you can nest the loops for each level of the array.

Example 1: In this example, we will use a Multidimensional array to iterate array items through foreach loop.

PHP
<?php

$numbers = array(
    array(10, 20, 30, 40, 50),
      array(15, 30, 45, 60, 75),
      array(20, 40, 60, 80, 100),
      array(25, 50, 75, 100, 125),
      array(30, 60, 90, 120, 150)
);  

foreach ($numbers as $number) {
    foreach ($number as $num) {
        echo "$num, ";
    }
      echo "\n";
}

?>

Output
10, 20, 30, 40, 50, 
15, 30, 45, 60, 75, 
20, 40, 60, 80, 100, 
25, 50, 75, 100, 125, 
30, 60, 90, 120, 150, 

Example 2: In this example, we will use Multidimensional associative array to iterate through foreach loop.

PHP
<?php

$students = array(
    array("name" => "Rakesh", "Age" => 25),
    array("name" => "Rajan", "Age" => 26),
    array("name" => "Akash", "Age" => 28)
);  

foreach ($students as $student) {
    foreach ($student as $key => $value) {
        echo "$key => $value\n";
    }
    echo "\n";
}

?>

Output
name => Rakesh
Age => 25

name => Rajan
Age => 26

name => Akash
Age => 28


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads