phparraysfor-loopmultidimensional-arraynested-for-loop

How to populate a 2d array from two for() loops


How can I use nested for() loops to get the following result?

$data = array(
    array('11', '12', '13'),
    array('21', '22', '23'),
    array('31', '32', '33'),
    array('41', '42', '43') 
);

How can I build that array using for loops like:

for ($x = 0; $x < 5; $x++) {
    for ($y = 0; $y < 4; $y++) {
        $data xxx;
    }
}

What is the code to replace in xxx?


Solution

  • Maybe:

    $data= array();
    for ($x = 1; $x < 5; $x++) {
        $data[$x]= array(); 
        for ($y = 1; $y < 4; $y++) {
            $data[$x][]= ($x*10)+($y);
        }
    }
    echo "<pre>";
    print_r($data);