Showing posts with label merge array. Show all posts
Showing posts with label merge array. Show all posts

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