1

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++;
   }
}
?>

4 Answers 4

4
$number = range(1,9);
print_r (array_chunk($number,3));
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

1

One of hundreds options:

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

Comments

0

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);
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.