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:

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

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

For this situation, the following will not work:

$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:

$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;
}

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:

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

2 thoughts on “Merging PHP Arrays with no conflicts”

Leave a Reply

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