Reputation: 13
I need to create two-dimensional array by using 2 loops. Array must look like this: [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
This is what I tried, but I wanted to see better solution and to know is my solution bad.
<?php
$arr = [];
$elem = 1;
for ($i = 0; $i <= 2; $i++) {
for ($j = 1; $j <= 3; $j++) {
$arr[$i][] = $elem++;
}
}
?>
Upvotes: 1
Views: 180
Reputation: 60
one method: this method use "temp variables".
<?php
$arr_inner = [];
$arr_main = [];
$elem=1;
for ($i = 0; $i <= 2; $i++) {
for ($j = 0; $j <= 2; $j++) {
$elem =$elem +1;
$arr_inner[$j] = $elem;
}
$arr_main[$i] = $arr_inner;
unset($arr_inner);
}
?>
Upvotes: 0
Reputation: 94672
Others have shown you some clever ways, but keeping it simple in case you are just starting out with programming.... In the inner loop, create a temporary array, then outside the inner loop but inside the outer, add it to your main array.
$arr = [];
$elem = 1;
for ($i = 0; $i <= 2; $i++) {
$t = []; #Init empty temp array
for ($j = 1; $j <= 3; $j++) {
$t[] = $elem++;
}
$arr[] = $t;
}
Upvotes: 1
Reputation: 54831
One of hundreds options:
$arr = [
range(1, 3),
range(4, 6),
range(7, 9),
];
print_r($arr);
Upvotes: 1