5 Ways to Merge Arrays in PHP (with Examples)

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

PHP, a server-side scripting language, is a powerful tool for web developers. Arrays are a fundamental part of programming in PHP, serving as a collection of elements, such as numbers, strings, or other arrays. Often times, developers need to merge multiple arrays into one for various reasons, such as data consolidation, sorting, or simply organizational purposes. This article takes a deep dive into the methods one can employ to merge arrays in PHP and the nuances of each method.

The array_merge Function

To merge two or more arrays in PHP, the array_merge function is commonly used. This function takes two or more arrays as inputs and combines them into a single array. The indices of the resulting array are renumbered starting from zero; this can also cause string keys to be overwritten if they occur in multiple arrays.

<?php
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("a" => "pear", "b" => "strawberry", "0" => "pineapple");
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
?>

This code will output:

Array
(
    [a] => pear
    [b] => strawberry
    [0] => apple
    [1] => banana
    [2] => pineapple
)

It’s vital to understand how the function treats keys so that developers do not unintentionally lose data.

In cases where only numeric keys are used, and the arrays should maintain their keys, another function should be considered, such as array_merge_recursive.

The array_merge_recursive Function

When more control over the array merging behavior is required, especially with associative arrays, array_merge_recursive comes into play. It behaves like array_merge, but when two or more array elements have the same key, it constructs an array of these elements rather than overwriting the key.

<?php
$array1 = array("a" => "apple", "b" => ["banana", "berry"]);
$array2 = array("a" => "avocado", "b" => "blackberry", "c" => ["cherry"]);
$mergedArray = array_merge_recursive($array1, $array2);
print_r($mergedArray);
?>

This would output:

Array
(
    [a] => Array
        (
            [0] => apple
            [1] => avocado
        )

    [b] => Array
        (
            [0] => banana
            [1] => berry
            [2] => blackberry
        )

    [c] => Array
        (
            [0] => cherry
        )

)

This function is useful for retaining all values associated with a key.

The + Operator

The union of two arrays can be achieved using the + operator. This operator appends the right-hand array to the left-hand array. Keys from the left-hand array will be preserved, and keys that exist in both arrays will use the values from the left-hand array.

<?php
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$combinedArray = $array1 + $array2;
print_r($combinedArray);
?>

This would result in:

Array
(
    [a] => apple
    [b] => banana
    [c] => cherry
)

Note that unlike array_merge, the + operator does not re-index numeric keys; it follows the same rules for associative keys as described above.

Using array_replace

For replacing elements from passed arrays into the first array recursively, developers can use the array_replace function. The function takes two or more arrays and returns a new array.

<?php
$array1 = array("a" => "apple", "banana");
$array2 = array(0 => "pear", "a" => "avocado", 1 => "grape");
$replacedArray = array_replace($array1, $array2);
print_r($replacedArray);
?>

The preceding code outputs the following:

Array
(
    [a] => avocado
    [0] => pear
    [1] => grape
)

With array_replace, keys are preserved, so ‘apple’ is replaced by ‘pear’ and ‘banana’ by ‘grape’.

Handling Multidimensional Arrays

For complex scenarios involving multidimensional arrays, a custom merging function might be necessary to achieve the desired goal. Here, array manipulation functions like array_walk_recursive, array_map, and user-defined functions come into play to provide granular control over the merge process.

At times, the merging strategy may involve considering the value types, unique keys constraints, or even sorting the final merged array with a criteria that reflects the merge’s purpose.

Example:

<?php
function custom_merge_arrays(array $array1, array $array2): array {
    $result = $array1;

    array_walk_recursive($array2, function($value, $key) use (&$result) {
        if (array_key_exists($key, $result) && is_array($value) && is_array($result[$key])) {
            // Recursive merge for nested arrays
            $result[$key] = custom_merge_arrays($result[$key], $value);
        } else {
            // Non-nested merge
            $result[$key] = $value;
        }
    });

    return $result;
}

// Example usage:
$array1 = [
    'name' => 'John',
    'age' => 30,
    'details' => [
        'city' => 'New York',
        'hobbies' => ['Reading', 'Traveling'],
    ],
];

$array2 = [
    'age' => 31,
    'details' => [
        'hobbies' => ['Photography'],
    ],
    'extra' => 'Additional Information',
];

$mergedArray = custom_merge_arrays($array1, $array2);

// Output the merged array
print_r($mergedArray);
?>

In this example, the custom_merge_arrays function recursively walks through the arrays, merging values according to specified conditions. It considers nested arrays and provides granular control over the merge process.

Conclusion

Merging arrays is a crucial skill for any PHP developer. There are multiple functions available in PHP for merging arrays, each with its own use case and set of behaviors. By understanding and appropriately applying array_merge, array_merge_recursive, array + operator, array_replace and other custom solutions, developers can master array manipulations, ensuring efficient and error-free code.