0

I have two associative array.

$Array1 = array(
 'abc'=> 'abc',
 'def'=> 'def'
);

$Array2 = array(
 '123'=> '123',
 '456'=> '456'
);

I am merging them using array_merge.

$Array3 = array_merge($Array1, $Array2);

Now value of $Array3 is like this.

Array
(
    [abc] => abc
    [def] => def
    [0] => 123
    [1] => 456
)

It looks really odd until I read php manual which says Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. array_merge manual

My questing How can I merge both array without loosing their associative keys. Both array can have common KEYS and I don't want to loose my information also. :(

3 Answers 3

1

By +:

$Array1 = array(
 'abc'=> 'abc',
 'def'=> 'def'
);

$Array2 = array(
 '123'=> '123',
 '456'=> '456'
);
var_dump($Array1 + $Array2);

This will preserve the index, but note this will not overwrite the value of the first array if same key exists in first array.

And if you want the overwrite working, then there is array_replace function for this:

var_dump(array_replace($Array1, $Array2));
Sign up to request clarification or add additional context in comments.

4 Comments

Both array can have common KEYS and I don't want to loose my information also. :(. I updated the question.
@RiteshChandora So what's the result you expected for that, 'common_key' => array('value1', 'value2') ?
both array are multidimensional. your code don't work for me.
array_replace_recursive() works well. thanks for help
1

Try this code :) it will work

    function my_merge($array1,$array2)
    {
       foreach($array2 as $key => $value)
       {
         $array1[$key] = $value;
       }
       return $array1;
    }

    $Array1 = array(
          'abc'=> 'abc',
          'def'=> 'def'
    );

     $Array2 = array(
           '123'=> '123',
           '456'=> '456'
     );

     $Array3 = my_merge($Array1, $Array2);

Comments

1

For associative arrays, use

$result = $Array1 + $Array2;

-but note, that for numeric keys this will also re-index:

$Array1 = array(
 'abc',
 'def'=> 'def'
);

$Array2 = array(
 '123',
 '456'
);
var_dump($Array1 + $Array2);
//array(3) { [0]=> string(3) "abc" ["def"]=> string(3) "def" [1]=> string(3) "456" } 

If you have same keys in your arrays, you can use:

$result = array_reduce(array_keys($Array1), function($c, $x) use ($Array1)
{
    $c[$x] = isset($c[$x])
       ?array_merge((array)$c[$x], [$Array1[$x]])
       :$Array1[$x];
    return $c;
}, $Array2);

2 Comments

Both array can have common KEYS and I don't want to loose my information also. :(. I updated the question.
Hm, I've updated (so in that case you'll have array of values for such keys)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.