Merging PHP Arrays with no conflicts

I was working on a recent project where I had multiple arrays of data which I needed to merge. No matter how powerful PHP is (and frustrating), there are always certain things you have to create yourself.

Here is an simple example of my arrays:
{code type=php}

$array1 = array(
“apples” => 2,
“oranges” => 3,
“bananas” => 2 );

$array2 = array(
“apples” => 2,
“oranges” => 1,
“kiwis” => 4 );

For this situation, the following will not work:
{code type=php}
$new_array = $array1 + $array2;

The reason this will not work is because there are duplicate keys. In both arrays, the keys “apple” and “orange” both exist. Here is my solution:

{code type=php}

$new_array = merge_arrays($array1, $array2);

function merge_arrays($arr1, $arr2) {
(is_array($arr1)) ? $new_array = $arr1: $new_array = array();

if (is_array($arr2)) {
foreach($arr2 as $key => $value) {
isset($new_array[$key])) ? $new_array[$key] += $value : $new_array[$key] = $value ;
return $new_array;
} {/code}

The first line checks to make sure the first argument passed is an array. Otherwise, it skips that value and creates a new array.

The if statement also checks to make sure that our second argument is also an array. Then it gets a little more complicated.

First, we set up a foreach loop to go through each element inside the second array. the array key is stored in $key, and the value in $value.

The only thing left to do is to check whether or not the key already exists in the new array. If it does, add onto the current value, otherwise create the key and value.

That’s it! You will get this as a result:

{code type=php}

$new_array = array(
“apples” => 4,
“oranges” => 4,
“bananas” => 2,
“kiwis” => 4 );

2 thoughts on “Merging PHP Arrays with no conflicts”

  1. I will only change this:
    `(is_array($arr1)) ? $new_array = $arr1: $new_array = array();`

    to this:

    `$new_array = (is_array($arr1)) ? $arr1: array();`

    Is is more readable and clean. Other thing is perfect.

Comments are closed.