Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP merging arrays without overwriting data

Tags:

arrays

merge

php

I have a number of arrays, and I wish to merge them without overwriting or losing any data. I believe they are called associative arrays but I am not 100% sure about the terminology .

The arrays contain information like this:

$array1['title']
$array1['description']

$array2['title']
$array2['description']
$array2['random information']

I want to merge the information contained within the common keys of $array1 and $array2 without overwriting any data.

Is this possible?

Things I have tried, that were not successful, include the following:

(array)$array3 = (array)$array1 + array($array2);

$array3 = array_push($array1,$array2);

 $array3 = array_merge_recursive($array1,$array2);

Essentially I want to retain the common keys, and add the information from both arrays into the new array. For example, I only want one ['title'] ['description'] etc in the new array but I want the information from both arrays in the new array.

So $array3 will contain all the information that was in $array1 and $array2... all the items from ['title'] ['description'] will be retained under ['title'] ['description'] in $array3.

Is this possible?

Thanks guys.

like image 392
Tom Avatar asked Sep 01 '25 05:09

Tom


1 Answers

I have found using array_replace_recursive nested works. This first call creates an array merged which may have some values removed, the second call will remerge back into your master array keeping all array keys from the master array but allowing the merged in array to overwrite values in the master.

 $mergedArray = array_replace_recursive($array2, array_replace_recursive($array1, $array2));
like image 82
Corey S. Avatar answered Sep 02 '25 17:09

Corey S.