Monday, October 19, 2009

Merging associative arrays in PHP

I've come across a problem recently when merging associative arrays in PHP using the array_merge function. The problem is that when one of the arrays has an element with a numeric key (even if the array is associative), the resulting array will be re-indexed as a numeric array. This is really how array_merge works so it is not a bug. A solution is to use the '+' operator to join the two arrays so the keys will be preserved. Here's an example:
$a = array(
'1'=> 'one',
);
$b = array(
'3'=> 'three',
'5'=> 'five'
);
print_r(array_merge($a, $b));
print_r($a + $b);

The output will be:

Array
(
[0] => one
[1] => three
[2] => five
)
Array
(
[1] => one
[3] => three
[5] => five
)

1 comment: