Merging arrays in php keeping the keys
Say you have two arrays with the following values in them:
$array1 = array(13=>'bad luck', 7=>'billion people'); $array2 = array(1=>'number');
And you want the final result to be
$final = (1=>'number', 13=>'billion people', 13=>'bad luck');
But when you merge arrays and using array_merge, u got the indexes being ripped out from the second or first array whose keys are numeric?
The result using array_merge would be
(0 => 'bad luck', 1 => 'billion people', 2 => 'number')
And you don’t want that
Here is a simple way – just use operator overloading of the plus sign
$array1 = array(13=>'bad luck', 7=>'billon population'); $array2 = array(1=>'number'); $merged = $array1 + array2;
Note: This is provided the keys are not overlapping, otherwise, the first array would take ownership of keeping the value.