The purpose of this post is simple: I’ve seen way too many uses of array_merge function with associative arrays in PHP. In most cases the “+” union operator should have been used and here’s why. Given:
<?php $a1 = array('abcd' => 'value 1'); $a2 = array(1234 => 'value 2'); var_export(array_merge($a1, $a2)); var_export($a1 + $a2); ?>
The result is as follows:
array ( 'abcd' => 'value 1', 0 => 'value 2', ) array ( 'abcd' => 'value 1', 1234 => 'value 2', )
I bet the latter is what you would need most of the time. Let’s list the behavior of the two methods:
- non-matching string keys: simplest case – both methods append all elements and produce merged result
- matching string keys: array_merge overrides from latter array; union operator keeps element from the former
- non-matching integer keys: array_merge re-keys latter array(s) as integer keys are available, starting from 0; union operator leaves original keys
- matching integer keys: array_merge re-keys and appends; union operator keeps element from the former array
Also consider the following:
<?php $key = "1234"; $a = array(); $a[$key] = "abc"; $a["$key"] = "abc"; $a["" . $key] = "abc"; $a[(string)$key] = "abc"; ?>
All of the above will result in an integer key! PHP will force anything that looks like an integer into an integer even if you explicitly specify a string. From PHP array documentation:
If a key is the standard representation of an integer, it will be interpreted as such (i.e. “8″ will be interpreted as 8, while “08″ will be interpreted as “08″).
This means all integer rules will apply when using these elements with array_merge – i.e. all of them will be re-keyed. Conclusion: if you are using associative arrays, you most likely need the “+” union operator to merge arrays and not the array_merge function. Just be mindful of the order in which they are added.