Ganesh Babu
Ganesh Babu

Reputation: 3670

Merging two arrays without changing key values 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?

Upvotes: 11

Views: 19917

Answers (5)

Asif Raihan
Asif Raihan

Reputation: 1

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
)

Upvotes: 0

Bere
Bere

Reputation: 1747

$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

Upvotes: 6

briosheje
briosheje

Reputation: 7436

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

Will print:

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

Upvotes: 0

Nil&#39;z
Nil&#39;z

Reputation: 7475

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

Upvotes: 0

lc.
lc.

Reputation: 116458

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]

Upvotes: 21

Related Questions