Search code examples
phparraysassociative-array

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?


Solution

  • 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.