Search code examples
phparray-merge

Array-Merge on an associative array in PHP


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
)

Solution

  • 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);
    
    ?>