0

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?

3
  • 7
    Can we see your code? Commented Oct 2, 2009 at 20:23
  • 5
    It's likely you're using the same value for $j and thus overriding parts of your array (if I'm understanding the problem correctly). Commented Oct 2, 2009 at 20:25
  • @Strager: Thanks a lot for pointing out the problem. I was not able to find it, may be because i never thought that way. Thanks again! :) Commented Oct 2, 2009 at 21:06

1 Answer 1

4

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);
?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.