开发者

What would be the best way to add two associative arrays such that duplicate values are not over written : `+` or `array_merge`? [duplicate]

This question already has answers here: + operator for array in PHP? (8 answers) 开发者_C百科 Closed 9 years ago.

What is the best way to add two associative arrays such that duplicate values are not over written : + or array_ merge ?

I was pretty sure that using + operator I can add two associative arrays such that duplicate values are not over written but this Answer is saying something different and so am not sure if it is really true.

I would really appreciate if you can share some lights on how can we add two associative arrays such that duplicate values are not over written.

Appreciate your time and responses.


An array can't have more than one key-value pair with the same key. So if you have:

$array1 = array(
  'foo' => 5,
  'bar' => 10,
  'baz' => 6
);

$array2 = array(
  'x' => 100,
  'y' => 200,
  'baz' => 30
);

If you combine these arrays, you only get to keep one of the values of the combined array. The methods you describe do two different things:

print_r(($array1 + $array2));

// Result:
// Array
// (
//     [foo] => 5
//     [bar] => 10
//     [baz] => 6
//     [x] => 100
//     [y] => 200
// )

print_r(array_merge($array1, $array2));

// Result:
// Array
// (
//     [foo] => 5
//     [bar] => 10
//     [baz] => 30
//     [x] => 100
//     [y] => 200
// )

So you really need to define what you want to happen when you combine the arrays.

UPDATE

Based on @davidosomething's answer, here's what happens if you do array_merge_recursive():

print_r(array_merge_recursive($array1, $array2));

// Result:
// Array
// (
//     [foo] => 5
//     [bar] => 10
//     [baz] => Array
//         (
//             [0] => 6
//             [1] => 30
//         )
// 
//     [x] => 100
//     [y] => 200
// )


You actually want array_merge_recursive This creates an array of arrays if the KEY is the same but the value is different

Both array_merge and union will DISCARD one of the VALUES if a duplicate key is found


If you want to keep both values, you have to change the key for at least one of them. Perhaps you can write your own method to merge two arrays which prefixes all keys.


array_merge will combine the arrays such that no values are lost, provided the arrays have contiguous numeric keys. If you start mixing string keys, values with the same keys will be overwritten. If you treat your arrays as arrays and not maps, array_merge will do what you want.


a picture is better than 1000 words

$a = array('foo' => 'A');
$b = array('foo' => 'B');

print_r($a + $b);              // foo=A
print_r(array_merge($a, $b));  // foo=B
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜