Effortlessly Merge Arrays: When to Use array_merge vs. the Splat Operator

jochelle mendonca
4 min readApr 5, 2024

--

As developers, we often find ourselves working with arrays, whether it’s combining them, manipulating their elements, or passing them as arguments to functions.

And mostly, we would often encounter the need to combine elements from multiple sources.

Photo by Vlad Hilitanu on Unsplash

Two popular methods for achieving this are the array_merge function and the spread/splat operator which was introduced in PHP 7.4.

As we discuss more on this, let's delve into their pros, cons, compare them, and uncover some hidden tips and tricks to help you make informed decisions, so to help you choose the best approach for your situation.

array_merge()

Let’s start with array_merge, a built-in PHP function that merges two or more arrays into a single array.

It’s a straightforward and versatile method for combining array elements, allowing you to merge associative arrays, indexed arrays, or a combination of both.

Here’s a simple example:

$array1 = ['a' => 1, 'b' => 2];
$array2 = ['c' => 3, 'd' => 4];

$result = array_merge($array1, $array2);
print_r($result);

Pros:

  • Supports merging multiple arrays of different types (associative, indexed, or mixed).
  • Well-established and widely used.
  • Preserves numeric keys, ensuring consistent array indexing.
  • Can merge arrays of any size without exceeding memory limits.
  • Can take a third argument to determine which values to overwrite in case of key conflicts.

Cons:

  • Returns a new array, potentially consuming additional memory for large arrays.
  • Does not handle nested arrays or objects automatically.
  • Numeric keys may be re-indexed, leading to unexpected behavior in certain scenarios.
  • Requires function call overhead compared to the concise syntax of the spread operator.

Splat/Spread Operator (…)

The splat operator (…) was introduced in PHP 5.6 as a convenient way to unpack arrays and pass their elements as arguments to functions or constructors.

It simplifies array manipulation and function calls, offering a concise syntax for working with array data.

Here’s how it works:

$array = ['a' => 1, 'b' => 2];

// Unpack array elements as function arguments
function exampleFunction($a, $b) {
echo $a + $b;
}

exampleFunction(...$array);

Pros:

  • Concise and expressive syntax for unpacking array elements.
  • Works seamlessly with functions, methods, and constructors.
  • Compatible with nested arrays and objects, providing flexibility in data manipulation.
  • Preserves the original arrays by default.

Cons:

  • Relatively new compared to array_merge.
  • Limited to unpacking arrays as function arguments, not for merging arrays directly.
  • Requires PHP 5.6 or later, limiting compatibility with older PHP versions.
  • May lead to less readable code in complex scenarios with multiple unpacking operations.

Should You Ditch array_merge Entirely?

The arrival of the spread operator sparked discussions about whether array_merge is obsolete. Here's a breakdown to help you decide:

When deciding between array_merge and the spread operator, consider your specific use case and requirements.

  • Readability: For simple merging where readability is a priority, the spread operator often shines due to its concise syntax.
  • Control and Flexibility: If you need precise control over merging behavior (e.g., recursive merging, key conflict resolution), array_merge offers more options.
  • Performance: While the spread operator might have a slight edge in some cases, prioritize readability and maintainability over micro-optimizations in most scenarios.

Comparing Performance:

When evaluating the performance of array_merge vs. the spread operator, consider the size and complexity of the arrays being manipulated.

For small to medium-sized arrays, array_merge typically performs well and offers versatility in array manipulation.

However, for scenarios involving extensive array unpacking for function arguments, the spread operator provides a more efficient and concise solution.

Hidden Tips and Tricks:

  • Use a ternary operator with array_merge to conditionally merge based on a condition.
$mergedArray = isset($array1) ? array_merge([], $array1) : $array2;
  • Use array_merge_recursive for merging arrays with nested structures, preserving nested arrays without overwriting their values.
  • Combine array_merge with the union operator (+) to merge arrays while preserving numeric keys and avoiding re-indexing. This optimizes array_merge performance by pre-allocating memory for the resulting array using array_merge and the union operator (+).
  • Experiment with the spread operator in conjunction with variadic functions to streamline function calls and improve code readability.
  • To unpack associative arrays with the spread operator, use array_keys and array_flip:
$mergedArray = [...array_flip(array_keys($array1)), ...$array2];

In the battle of array_merge vs. the spread operator, there’s no one-size-fits-all solution. Each method has its strengths and weaknesses, making them suitable for different scenarios.

Ultimately, the best approach depends on your specific project requirements and coding style.

Do let me know, which one would/do you use and why?

Want to read more on arrays, check my post here

If you liked this article and would like to support me, make sure to:

  • 👏Clap for this story
  • 🔔Follow me on Medium
  • ☕️ If you feel my work is worth an appreciation, you can buy me a coffee!

--

--

jochelle mendonca

Passionate PHP developer. Enthusiastic about the power of words, equally adept at reading and writing