1

I have an array $products and I this is how i add elements to it.

$products[] = ['name'=>'prod1', 'qty'=>'5', 'price'=>'20'];
$products[] = ['name'=>'prod2', 'qty'=>'10', 'price'=>'30'];
$products[] = ['name'=>'prod3', 'qty'=>'15', 'price'=>'40'];

My question is, is there a way to add all three sets of elements in a single syntax. for example:

$products[] = ['name'=>'prod1', 'qty'=>'5', 'price'=>'20'],
              ['name'=>'prod2', 'qty'=>'10', 'price'=>'30'],
              ['name'=>'prod3', 'qty'=>'15', 'price'=>'40'];
3
  • 1
    that's wrong code Commented Jan 12, 2020 at 0:13
  • All you can do is to use array_merge, but to use it, you need to create an array with the new items you want to add. I'm not sure it is interesting. Commented Jan 12, 2020 at 0:18
  • But I don't think it is a better way than adding items one by one. Commented Jan 12, 2020 at 0:24

1 Answer 1

1

You could use array_push

Example:

array_push($products, 
  ['name'=>'prod1', 'qty'=>'5', 'price'=>'20'],
  ['name'=>'prod2', 'qty'=>'10', 'price'=>'30'],
  ['name'=>'prod3', 'qty'=>'15', 'price'=>'40']
);

Sandbox

Sign up to request clarification or add additional context in comments.

Comments

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.