Iterating Over Multidimensional Arrays in PHP
Let's now learn how to iterate over multidimensional arrays using loops. Suppose we have the following array:
<?php
$arr = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
];
?>
As you can see, this array is two-dimensional, which
means that to iterate through it, two nested
foreach
loops are needed:
<?php
foreach ($arr as $sub) {
foreach ($sub as $elem) {
echo $elem;
}
}
?>
Given the following array:
<?php
$arr = [[1, 2, 3], [4, 5, 6, 7], [8, 9]];
?>
Using two nested loops, find the sum of the elements of this array.