Awan
Awan

Reputation: 18560

Merge two numerically-keyed associative arrays and preserve the original keys

I have two arrays like this:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

I have tried this but it is changing their original keys:

$output = array_unique( array_merge( $array1 , $array2 ) );

Any solution?

Upvotes: 110

Views: 238004

Answers (11)

Anil Kumar Thakur
Anil Kumar Thakur

Reputation: 17

We can combine two arrays in PHP using the spread operator (...).

In this example, $array1 contains the values 1 through 10, and $array2 contains the values 11 through 20. The spread operator is used to concatenate(combine) the two arrays into a single array called $data.

// Define the first array
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Define the second array
$array2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

// Use the spread operator to concatenate the two arrays into a single array
$data = [...$array1, ...$array2];

// Print the contents of the combined array
print_r($data);

Upvotes: -2

Antony
Antony

Reputation: 4340

This is slightly explored by @jchook in one of his comments, but it is worth highlighting that the + is not as consistant as one might expect. When you are dealing with keys which are the same, the results are not the same as array_merge.

$a1 = array(
    'hello',
    'world',
);

$a2 = array(
    'foo',
    'baz',
);

// Will NOT work - only outputs $a1
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    'a' => 'hello',
    'b' => 'world',
);

$a2 = array(
    'c' => 'foo',
    'd' => 'baz',
);

// Will work (however were a and b c and d - would equally fail
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    1=> 'hello',
    2=> 'world',
);

$a2 = array(
    3=>'foo',
    4=>'baz',
);

// Will work
print'<pre>';print_r($a1 + $a2);print'</pre>';

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131861

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in: http://php.net/manual/en/function.array-merge.php

Upvotes: 193

Michas
Michas

Reputation: 9428

This works:

$output = $array1 + $array2;

Upvotes: 32

Shoaib Ahmed
Shoaib Ahmed

Reputation: 781

The new way of doing it with php7.4 is Spread operator [...]

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);

Spread operator should have better performance than array_merge

A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.

Upvotes: 13

Rafi Ullah Patel
Rafi Ullah Patel

Reputation: 124

https://www.php.net/manual/en/function.array-merge.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Upvotes: 0

Student of Science
Student of Science

Reputation: 492

If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

function getArr() {
  return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']

$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']

function arrGen() {
    for($i = 11; $i < 15; $i++) {
        yield $i;
    }
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]

It works like in JavaScript ES6.

See more on https://wiki.php.net/rfc/spread_operator_for_array.

Upvotes: 1

Norman Edance
Norman Edance

Reputation: 392

Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()

array_unique(array_merge($a, $b), SORT_REGULAR);

Notice:

5.2.10+ Changed the default value of sort_flags back to SORT_STRING.

5.2.9 Default is SORT_REGULAR.

5.2.8- Default is SORT_STRING

It perfectly works. Hope it helps same.

Upvotes: 1

inemanja
inemanja

Reputation: 1371

You should take to consideration that $array1 + $array2 != $array2 + $array1

$array1 = array(
'11' => 'x1',
'22' => 'x1' 
);  

$array2 = array(
'22' => 'x2',
'33' => 'x2' 
);

with $array1 + $array2

$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);

and with $array2 + $array1

$array2 + $array1 = array(  
'11' => 'x1',  
'22' => 'x2',  
'33' => 'x2'  
);

Upvotes: 39

jeni
jeni

Reputation: 440

This works:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

Upvotes: 1

Brendan Bullen
Brendan Bullen

Reputation: 11798

To do this, you can loop through one and append to the other:

<?php

$test1 = array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

$test2 = array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);


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

print_r(combineWithKeys($test1, $test2));

?>

UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);

Upvotes: 4

Related Questions