0

I have an array that contains 4 elements (sub-arrays).

$orders = array( array(), array(), array(), array() );

Now, I want to tell each sub-array to append items to itself, so I iterate through them like so:

for($i=0; $i<4 ; $i++ ) {
  $orders[$i][] = rand();     // this does not work, unexpected '['
}

What is a better way for accomplishing this?

Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • @Saty that was a typo. I fixed it. Thanks. – Ahmad May 24 '16 at 12:20
  • Just so funny, that your code is works. What do you mean not work? I think the typo was your problem: `$<4` – vaso123 May 24 '16 at 12:24
  • The only "better" way would be to use a foreach loop so that you do not have to go back into your code 4.37 years from now and debug an issue which stems from an associative array being passed into this code which is only suited for indexed arrays. – MonkeyZeus May 24 '16 at 12:29
  • defiantly you have typo `$<4` here . It is working in every version of php https://3v4l.org/hIpM3 – Saty May 24 '16 at 12:31

1 Answers1

3

You had a syntax error:

for($i=0; $i<4 ; $i++ ) {
   $orders[$i][] = rand();     // this does not work, unexpected '['
}

But this might be even better:

foreach($orders as $key => $order){
    $orders[$key][] = rand();
}
Jan
  • 42,290
  • 8
  • 54
  • 79
Andrey
  • 441
  • 2
  • 7