Skip to content
Home » Merge 2+ PHP arrays with the Same Keys | 2023 Code Examples

Merge 2+ PHP arrays with the Same Keys | 2023 Code Examples

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. 

Merge 2 PHP Arrays with Same Key Recommended Code 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
)
*/

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 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.

How to 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.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources. We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Merging Multiple Arrays with Same Keys in PHP

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