Roeland
Roeland

Reputation: 3858

merge two arrays, while maintaining the numeric keys

im trying to merge two arrays together. both have numeric keys and are unique. when i use array_merge, it re-indexes starting at 0.

so lets say i have

[2] = abc
[5] = cde

and i have

[32] = fge
[13] = def

i want to merge these two together maintaining the unique keys.

below is the explaination on the current merge behavior.. any way around this?

"If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero."

Upvotes: 13

Views: 6149

Answers (5)

Marek Granecki
Marek Granecki

Reputation: 71

if you want to merge arrays with numeric keys, keep the keys and override items from first array by items from second one:

$a = array(0 => "a", 1 => "b"); 
$b = array(1 => "c", 5 => "d"); 
var_dump(array_diff_key($a, $b) + $b);

will produce:

array(3) {   
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "c"
  [5]=>
  string(1) "d"
}

Upvotes: 7

Naveed
Naveed

Reputation: 42113

$result = array(2 => 'abc', 5 => 'cde') + array(32 => 'fge', 13 => 'def');
print_r($result);

Upvotes: 1

Manie
Manie

Reputation: 2028

Try this:

$arr1 = array();
$arr2 = array();
$arrmerge = array();
array_push($arr, $arr1, $arr2);

$arr1 and $arr2 will be merge and stored in $arrmerge. You can access it by foreach.

Hope it works!

Upvotes: 0

Matt Huggins
Matt Huggins

Reputation: 83299

Try using the + operator.

$one = array(2 => 'abc', 5 => 'cde');
$two = array(32 => 'fge', 13 => 'def');
$three = $one + $two;

$three should now look like this:

[2] = abc
[5] = cde
[32] = fge
[13] = def

Upvotes: 19

deceze
deceze

Reputation: 522412

Try the array union operator +.

Upvotes: 2

Related Questions