Iterating Over a Three-Dimensional Array in PHP
But to iterate over a three-dimensional array, three nested loops are needed. Let's say for example we have the following array:
<?php
$arr = [
[
['a', 'b'],
['c', 'd'],
],
[
['e', 'f'],
['g', 'h'],
],
[
['i', 'j'],
['k', 'l'],
],
];
?>
Let's output all its elements to the screen:
<?php
foreach ($arr as $sub) {
foreach ($sub as $subsub) {
foreach ($subsub as $elem) {
echo $elem;
}
}
}
?>
Given the following array:
<?php
$arr = [
[
[1, 2, 3],
[6, 7, 8],
[3, 8, 4],
[6, 7, 9],
],
[
[9, 1, 2],
[4, 5, 6],
],
[
[9, 1, 2],
[4, 5, 6],
[5, 6, 3],
],
];
?>
Using three nested loops, find the sum of the elements of this array.