Thursday, January 29, 2009

Merging Arrays Preserving the Numeric Keys

Merging arrays like this:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

will result to:

Array
(
[0] => data
)

Don't forget that numeric keys will be renumbered!

If you want to completely preserve the arrays and just want to append them to each other (not overwriting the previous keys), use the + operator:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>

The numeric key will be preserved and thus the association remains.

Array
(
[1] => data
)

Source: http://php.net/array_merge

5 comments:

malak said...

this "renumbering" behaviour is really unexpected.

php programmer said...

php is server side scripting language, it is open source we can easily embed in to html document renumbering fuction and application is program is good source for learners

Unknown said...

thanks i was looking for such function for ages.

Anonymous said...

Thanks a lot :)

Jonathan said...

carefull! the second array won't overwrite any items of the first one.