Filling Multidimensional Arrays with Numbers in Order in PHP
In the previous examples, all numbers in the subarrays were the same. Let's now make it so that the numbers increase, like this:
<?php
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
?>
To do this, you need to create a special counter variable
that will increase its value by
1 on each iteration of the inner
loop. We will write the value of this counter
into the array, like this:
<?php
$arr = [];
$k = 1; // counter
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$arr[$i][$j] = $k; // write the counter
$k++; // increment the counter
}
}
var_dump($arr);
?>
You can reduce the code by moving the counter definition
into the first loop, and k++ - into the second:
<?php
$arr = [];
for ($i = 0, $k = 1; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++, $k++) {
$arr[$i][$j] = $k;
}
}
var_dump($arr);
?>
You can also increment the counter after assignment:
<?php
$arr = [];
for ($i = 0, $k = 1; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$arr[$i][$j] = $k++;
}
}
var_dump($arr);
?>
Please note that in this case it must be
k++, and not ++k, as the second option
will first increment the counter, and only then write
to the array (so the array will start with two,
not one).
Using two nested loops, form the following array:
<?php
[[1, 2], [3, 4], [5, 6], [7, 8]]
?>
Using two nested loops, form the following array:
<?php
[[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]
?>
Using three nested loops, form the following three-dimensional array:
<?php
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
?>