1

How do I add another multidimensional array to an already existing array.

$args = array('a'=>1,'b'=>2,'c'=>3);

Then I want to add 'd'=>4 to the already set array. I tried:

$args[] = array('d'=>4);

But I end up getting

Array ( [a] => 1 [b] => 2 [c] => 3 [0] => Array ( [d] => 4 ) ) 

Instead of

Array ( [a] => 1 [b] => 2 [c] => 3 [0] => [d] => 4 )

What is the correct way to achieve this result?

2
  • Are you looking to explicitly set [d]=>4 or did you want a more general solution? Commented May 21, 2015 at 19:39
  • These arrays do not appear to be multidimensional. Commented May 21, 2015 at 19:42

2 Answers 2

2

This is a simple example that only works if you want to explicitly set key d to 4. If you want a more general solution, see the other answers. Since the other answers did not mention the explicit solution, I thought I would.

You tried this:

$args[] = array('d'=>4);

What this did was add the array ['d'=>4] as a new entry to the existing $args array. If you really wanted to set the value of $args['d'] to 4 then you can do it directly:

$args['d'] = 4;

PLEASE NOTE:
This is an explicit answer. It will overwrite key d if it already exists. It is not useful for adding new entries to the array since you'd have to manually do so. This is only to be used if you just want to set one element no matter what and be done. Do not use this if you need a more general solution.

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

Comments

1

Use array_merge($myArray, array('d' => 1234)) http://php.net/manual/en/function.array-merge.php

$args = array('foo' => 1);
$args = array_merge($args, array('bar'=>2));

This will make $args

array => [
   'foo' => 1,
   'bar' => 2
]

3 Comments

array_merge($args, array('d' => 4)); gave me Array ( [a] => 1 [b] => 2 [c] => 3 ) , so it didnt seem to add it.
It does not modify your original array. If you want $args to still be it you'll need to do $args = array_merge($args, array('d' => 4))
Oh I see you need to add it to the variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.