Array Merge Keep N 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
	)

Share with:


4 comments
  1. @Edit: of course, we could switch the items (ie. array2+array1 => preserving the values of the second). By taking this in consideration the solution might work so there is a good reason being so popular :-)

  2. That’s not a good solution, despite the fact that is a very popular solution among PHP devs.

    The idea behind merging is to (e)merge the elements not to make a union. When merging two equal elements the value of the last will override the former. On the contrary, in the union (+ operator) the first element has a higher priority than the last one.

    For instance:
    $array1=array(‘key1’=>’value1′,’key2’=>’value2’);
    $array2=array(‘key1’=>’xxxx’,’key2’=>’value2′);

    By merging $array1+$array2 you get an $result like this:
    $result=(‘key1’=>’xxx’,’key2’=>’value2′);
    By union (aka +) you get:
    $result=(‘key1’=>’value1′,’key2’=>’value2’);

    There is no win-win solution as far as I know: you either lose the keys or the values.

  3. Very nice explanation about to combine two array using PHP built in function and + operator.

    Thank You.

Leave a Reply

Login with:



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