Array-Merge on an associative array in PHP

benhowdle89 picture benhowdle89 · Jul 25, 2011 · Viewed 19.8k times · Source

How can i do an array_merge on an associative array, like so:

Array 1:

$options = array (
"1567" => "test",
"1853" => "test1",
);

Array 2:

$option = array (
"none" => "N/A"
);

So i need to array_merge these two but when i do i get this (in debug):

Array
(
    [none] => N/A
    [0] => test
    [1] => test1
)

Answer

DhruvPathak picture DhruvPathak · Jul 25, 2011

try using :

$finalArray = $options + $option .see http://codepad.org/BJ0HVtac Just check the behaviour for duplicate keys, I did not test this. For unique keys, it works great.

<?php

$options = array (
                  "1567" => "test",
                  "1853" => "test1",
                  );


$option = array (
"none" => "N/A"
);


$final = array_merge($option,$options);

var_dump($final);


$finalNew = $option + $options ;

var_dump($finalNew);

?>