mkamthan
mkamthan

Reputation: 2371

Populate a multidimensional array while looping

I have an array declared above the beginning of a for loop as: $array = array();. Now, in the for loop I start inserting values into it. At some point I make one of its index as another array as $array[$j]=array(); And insert some values like, $array[$j][$l] = id; and so on.

Now, when I use print_r($array); inside the loop I get the expected value of the array. But outside the loop this newly created array (2-D) is getting lost and I am getting only a 1-D array as an output.

Can someone please tell me where the problem could lie?

Upvotes: 0

Views: 307

Answers (1)

Topher Fangio
Topher Fangio

Reputation: 20667

The following code works properly. Perhaps you are switching your variables as strager suggests.

<?php
$array = array();

for ($i = 0; $i < 10; $i+=1) {
    if ($i == 5) {
        $array[$i] = array('value 1', 'value 2');
    } else {
        $array[$i] = $i;
    }
}

print_r($array);
?>

Upvotes: 4

Related Questions