now we will use nested foreach loop to display the data from the given two multidimensional array.
See Example
<?php $students = [ 'student1' => ['name' => 'Rahul', 'age'=>21, 'class'=> 9], 'student2' => ['name' => 'Gargi', 'age'=>25, 'class'=> 10], 'student3' => ['name' => 'Jyoti', 'age'=>19, 'class'=> 12], ]; foreach($students as $key => $student) { echo 'data of '.$key.'<br>'; /*here $student is an array */ foreach($student as $key2 => $value) { echo $key2.' : '.$value.'<br>'; } } ?>
Output
data of student1 name : Rahul age : 21 class : 9 data of student2 name : Gargi age : 25 class : 10 data of student3 name : Jyoti age : 19 class : 12
So in this way we do traversal using Multidimensional Array foreach loop in PHP, although it is not necessary that you use foreach loop only, you can also use for loop.
PHP Traversing Multidimensional Array Using for loop
To traverse through a for loop, we will take the example of Two Multidimensional Indexed Array, although you can also traversal the Associative Array through a foreach loop but then we have to extract the array keys.
Example–
<?php $students = [ ['Rahul',25,9], ['Gargi',28,10], ['Jyoti',19,12], ]; $size = count($students); for($s=0; $s<$size; $s++) { echo 'data of studnet'.($s+1).'<br>'; /*now get inner array size */ $in_size = count($students[$s]); for($i=0; $i<$in_size; $i++) { echo $students[$s][$i].'<br>'; } } ?>
Output
data of studnet1 Rahul 25 9 data of studnet2 Gargi 28 10 data of studnet3 Jyoti 19 12