Filling Multidimensional Arrays in PHP
Suppose now we want to create some multidimensional array with numbers in a loop.
For example, the following two-dimensional array:
<?php
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
?>
Let's solve the task by using two nested loops. The outer loop will create subarrays, and the inner one will fill these subarrays with numbers:
<?php
$arr = [];
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$arr[$i][$j] = $j + 1; // filling the subarray with numbers
}
}
var_dump($arr);
?>
Form the following array using two nested loops:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Form the following array using two nested loops:
[['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x']]
Form the following array using three nested loops:
[
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
]