Edil
Edil

Reputation: 13

Create two-dimensional array by using 2 loops

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

Answers (4)

Fernand
Fernand

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

RiggsFolly
RiggsFolly

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

aryanknp
aryanknp

Reputation: 1167

$number = range(1,9);
print_r (array_chunk($number,3));

Upvotes: 4

u_mulder
u_mulder

Reputation: 54831

One of hundreds options:

$arr = [
    range(1, 3), 
    range(4, 6), 
    range(7, 9), 
];
print_r($arr);

Upvotes: 1

Related Questions