Merging two arrays without changing php key values

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 combine two arrays. The array_merge function successfully combined the two of them, but the key value has changed. I need the following output

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

What function can I use in php to get the following result without changing key values?

+7
arrays php
source share
5 answers

From the documentation , example # 3:

If you want to add the elements of an array from the second array to the first array without overwriting the elements from the first array and not re-indexing, use the array join 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 to the first array will be saved. If an array key exists in both arrays, then an element from the first array will be used, and the corresponding key 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" } 

So try: $a[0] + $b[0]

+14
source share

 $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 to this question

+2
source share

Try:

 $final = array(); $a=array('0'=>array('500'=>'1','502'=>'2')); $b=array('0'=>array('503'=>'3','504'=>'5')); foreach( $a as $key=>$each ){ $final[$key] = $each; } foreach( $b as $key=>$each ){ $final[$key] = $each; } print_r( $final ); 
0
source share
 $a=array('0'=>array('500'=>'1','502'=>'2')); $b=array('0'=>array('503'=>'3','504'=>'5')); $c = $a[0] + $b[0]; print_r($c); 

It will be printed:

 Array ( [500] => 1 [502] => 2 [503] => 3 [504] => 5 ) 
0
source share
 Just write : <?php $a = array(2=>'green', 4=>'red', 7=>'yellow',3=>'Green'); $b = array(8=>'avocado'); $d = $a+$b; echo'<pre>'; print_r($d); ?> 

out put:

 Array ( [2] => green [4] => red [7] => yellow [3] => Green [8] => avocado ) 
0
source share

All Articles