Tash Pemhiwa Tash Pemhiwa - 2 years ago 123
PHP Question

PHP array_merge key order

Does it matter in what order the keys in an array array doing an array_merge, i.e. would the keys in the second array below override the keys in the first array:

array1 = array('username' => 'abc', 'level' => 'admin', 'status' => 'active');
array2 = array('level' => 'root', 'status' => 'active', 'username' => 'bcd');


? Or would the order of the keys have to be the same in the two arrays?

Answer Source

The manual states the answer to this question:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So, yes the keys in the second array will overwrite the keys from the first one if the second array contains some of the same keys.

$array1 = array('username' => 'abc', 'level' => 'admin', 'status' => 'active');
$array2 = array('level' => 'root', 'status' => 'active', 'username' => 'bcd');

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

print_r($new);

Output:

Array
(
    [username] => bcd
    [level] => root
    [status] => active
)

So you can see that the keys from the second array overwrote the same keys from first one; the order of the keys in each array does not matter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download