Vivian Kennedy
Vivian Kennedy

Reputation: 121

Add an associative element to an associative array

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?

Upvotes: 1

Views: 58

Answers (2)

Muhammad Abdul-Rahim
Muhammad Abdul-Rahim

Reputation: 2010

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.

Upvotes: 2

Squeegy
Squeegy

Reputation: 869

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
]

Upvotes: 1

Related Questions