3 best ways to merge 2+ PHP arrays with the same keys

Summary:

There are 3 ways we can merge 2 arrays that contain the same key. The right solution depends on whether you use strings or integers for the keys. array_merge can be used with integers and a custom array_combine method is good when they're strings.

Learn how to merge 2 arrays same keys using PHP

We have seen various functions for merging PHP arrays. In this article, we will see how to merge two arrays with same keys PHP. Every function has a different mechanism when it comes to similar keys. Some functions overwrite the values while others retain the values. We will explore different options. However, it is recommended to read about the functions that we will eventually be using here.

As we have mentioned already, every function deals with similar keys differently. There’s also a distinction between integer keys and string keys. So, let’s see these functions and understand the related quirks. 

Option 1: Merge 2 arrays with the same keys PHP using array_merge function

PHP array_merge is an excellent function to merge arrays with same keys in PHP. However, it overwrites the values when keys are strings, but it could reindex numeric keys. Here’s an example with numeric keys.


$arr1 = [
    0 => "Zero",
    1 => "One",
    2 => "Two",
    3 => "Three",
    4 => "Four",
    5 => "Five"
];
 
$arr2 = [
    0 => "Six",
    1 => "Seven",
    2 => "Eight",
    3 => "Nine",
    4 => "Ten"
];
 
$merged = array_merge($arr1, $arr2);
 
print_r($merged);
 
/*
OUTPUT
Array
(
    [0] => Zero
    [1] => One
    [2] => Two
    [3] => Three
    [4] => Four
    [5] => Five
    [6] => Six
    [7] => Seven
    [8] => Eight
    [9] => Nine
    [10] => Ten
)
*/

Voila! It had merged arrays with similar keys by reindexing them. However, we don’t have the same privilege when keys are strings. Let’s confirm it through an example.


$array1 = ["Emp#1"=>"Franklin","Emp#2"=>"Richard","Emp#3"=>"Jake"];
$array2 = ["Emp#4"=>"Tyson","Emp#2"=>"Narnie","Emp#5"=>"Kylie"];
 
$merged_array = array_merge($array1, $array2);
 
print_r($merged_array);
 
/*
OUTPUT
Array
(
    [Emp#1] => Franklin
    [Emp#2] => Narnie  
    [Emp#3] => Jake    
    [Emp#4] => Tyson  
    [Emp#5] => Kylie  
)
*/

See! It just overwrites “Emp#2”. Instead of retaining both the values, it simply overwrites the previous value with the latest, “Richard” with “Narnie” in the example. So, we do not want to lose information to overwriting, and that’s why we have another fantastic function to tackle this problem, and that is the one we will see next.

Option 2: Merge multiple PHP arrays with the same keys using array_merge_recursive function

PHP array_merge_recursive recursively merges arrays. Recursion enables it to merge 2 arrays with same keys PHP such that it retains value in an array rather than overwriting them. Let’s see that in the following example.

$array1 = ["Emp#1"=>"Franklin","Emp#2"=>"Richard","Emp#3"=>"Jake"];
$array2 = ["Emp#4"=>"Tyson","Emp#2"=>"Narnie","Emp#5"=>"Kylie"];
 
$merged_array = array_merge_recursive($array1, $array2);
 
print_r($merged_array);

/*
OUTPUT
Array
(
    [Emp#1] => Franklin
    [Emp#2] => Array
        (
            [0] => Richard
            [1] => Narnie
        )
 
    [Emp#3] => Jake
    [Emp#4] => Tyson
    [Emp#5] => Kylie
)
*/

You can see that is the same example used before. However, array_merge_recursive merge arrays with same keys PHP by appending their values in an array instead of overwriting the previous one with the latest, just as the array_merge did. Cool, isn’t it? There’s yet another function that we can use. Let’s see that as well.

Option 3: Merge 2 arrays with the same keys in PHP using array_combine

PHP array_combine works slightly differently than the two functions we have seen already. It takes an array of keys and values and merges them. However, it does overwrite the preceding value with the latest. Let’s see how.

$keys = ["A","B","B","C"];
$values = [1,2,3,4];
 
$combined_arr = array_combine($keys,$values);
 
print_r($combined_arr);
 
/*
OUTPUT
Array      
(
    [A] => 1
    [B] => 3
    [C] => 4
)
*/

So, it doesn’t match the first occurrence of the similar key with its corresponding value. Luckily, we have a workaround for it. Let’s check it out.

function array_combine_($keys, $values){
    $result = array();
 
    foreach ($keys as $i => $k) {
     $result[$k][] = $values[$i];
     }
 
    array_walk($result, function(&$v){
     $v = (count($v) == 1) ? array_pop($v): $v;
     });
 
    return $result;
}

This function is explained in detail in the relevant article. If you’re eager to understand it in depth, then do read the article. Referring back to the example, it merge arrays with same key PHP as.

/*
OUTPUT
Array      
Array
(
    [A] => 1
    [B] => Array
        (
            [0] => 2
            [1] => 3
        )
 
    [C] => 4
)
*/

This time it retains the values corresponding to similar keys. So, we have explored all these options and it’s time to wrap this article up.

Conclusion

In this article, we have seen various options to merge arrays with same keys PHP. We have revisited functions like array_merge, array_merge_recursive, and array_combine. Each of these functions deals with merging arrays with similar keys differently. The array_merge_recusrive seems the most viable option if you do not want to lose the data.

However, this fact does not imply that the other two functions have no use. Infact some scenarios might require overwriting than retaining data, and that’s what array_merge does precisely. So, that’s all about this article. We hope you have learned something new today. Stay tuned for more interesting PHP articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

PHP array_combine: How to use with examples in PHP

array_merge_recursive: How to sue with examples in PHP

PHP array_filter: How to use with examples in PHP


Article Categories

Article Tags

© 2022 Confident.Systems