Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two arrays without changing key values php

Tags:

arrays

php

I have two arrays in php as shown in the code

<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>

I need to merge two arrays. array_merge function successfully merged two of them but key value gets changed. I need the following output

  Array
    (
        [0]=>Array(
           [500] => 1
           [502] => 2
           [503] => 3
           [504] => 5
         )
    )

What function can I use in php so that the following output is obtained without changing key values?

like image 790
Ganesh Babu Avatar asked Sep 09 '13 08:09

Ganesh Babu


People also ask

How do I merge two arrays with the same key?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How do I combine two arrays into a new array?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


2 Answers

From the documentation, Example #3:

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Therefore, try: $a[0] + $b[0]

like image 70
lc. Avatar answered Sep 22 '22 13:09

lc.


$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));

$c = $a + $b; //$c will be a merged array

see the answer for this question

like image 45
Bere Avatar answered Sep 22 '22 13:09

Bere