Google News
logo
PHP Program to Loop through a multidimensional array
In the following example of PHP program that demonstrates how to loop through a multidimensional array using nested `foreach` loops :
Program :
<?php

// Create a multidimensional array
$students = array(
    array("name" => "John", "age" => 25, "grades" => array(80, 90, 85)),
    array("name" => "Mary", "age" => 30, "grades" => array(95, 85, 90)),
    array("name" => "Bob", "age" => 35, "grades" => array(70, 75, 80))
);

// Loop through the array and print the values
foreach($students as $student) {
    echo "Name: " . $student["name"] . "<br>";
    echo "Age: " . $student["age"] . "<br>";
    echo "Grades: ";
    foreach($student["grades"] as $grade) {
        echo $grade . " ";
    }
    echo "<br><br>";
}

?>
Output :
Name: John
Age: 25
Grades: 80 90 85 

Name: Mary
Age: 30
Grades: 95 85 90 

Name: Bob
Age: 35
Grades: 70 75 80 
In the above example, we have created a multidimensional array `$students` that contains three sub-arrays, each representing a student with their name, age, and grades.

The grades for each student are stored in a nested array. We use nested `foreach` loops to iterate through the array and print the values of each element.

The outer `foreach` loop iterates through the `$students` array and assigns each sub-array to the `$student` variable. We use this variable to access the values of the elements in the sub-array, such as the student's name and age.

The inner `foreach` loop iterates through the "grades" sub-array for each student and assigns each grade to the `$grade` variable. We use this variable to output the grades for each student.

By using nested `foreach` loops, we can loop through a multidimensional array and access each element in a structured way.