Array Merging in PHP preserving keys. array_merge reindexing arrays

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.

Do you know how to run single phpunit test

Know who is calling your php script browser or script?

Find the pairs that makes K Complementary in the given array java solution

$_POST vs $HTTP_RAW_POST_DATA vs php://input and enctype

how to deploy symfony application to the production server

Deploying Symfony on Production Server

Run single phpunit test

composer install-update killed on vagrant machine

Leave a Reply

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

*
*