Array Merge Preserve Keys PHP

While merging two arrays in a new array through array_merge function, it resets the array keys (in integer) and sets the keys in ascending order like starting from 0 and onwards.

Save Array Keys While Merging Arrays In PHP

If you want to merge two or more arrays into a new array, array_merge is the function which fulfils this need. But this resets the array keys from 0 like:
// array 1
$arr1[1] = 1;
$arr1[2] = 2;
$arr1[3] = 3;

// array 2
$arr2[10] = 10;
$arr2[11] = 11;
$arr2[12] = 12;

$arr = array_merge($arr1,$arr2);
print_r($arr);

// result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 10
[4] => 11
[5] => 12
)

Solution – Preserve Array Keys While Merging

To prevent and save array keys, you can use the (plus) + sign instead of array_merge function as below:

// array 1
$arr1[1] = 1;
$arr1[2] = 2;
$arr1[3] = 3;

// array 2
$arr2[10] = 10;
$arr2[11] = 11;
$arr2[12] = 12;

$arr = $arr1 + $arr2;
print_r($arr);

// result:
Array
(
[1] => 1
[2] => 2
[3] => 3
[10] => 10
[11] => 11
[12] => 12
)

Leave a Reply

Your email address will not be published. Required fields are marked *