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?

4
  • @Saty that was a typo. I fixed it. Thanks. Commented May 24, 2016 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 Commented May 24, 2016 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. Commented May 24, 2016 at 12:29
  • defiantly you have typo $<4 here . It is working in every version of php 3v4l.org/hIpM3 Commented May 24, 2016 at 12:31

1 Answer 1

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

2 Comments

or use array_push($orders[$key], rand()); but it is the same.
And you had a typo :)

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.