Understanding array_merge(...$names) in PHP: Combining Arrays Efficiently

Understanding array_merge(...$names) in PHP: Combining Arrays Efficiently
Photo by Grooveland Designs / Unsplash

When working with PHP, you might encounter different ways to manipulate and merge arrays. One such example is this simple but powerful line of code:

$names = array_merge(...$names);

At first glance, it may seem a bit unfamiliar to beginners, but once you understand it, you'll find it extremely useful in certain scenarios. Let's break it down step by step.

What is array_merge?

The function array_merge is one of PHP's built-in functions for combining arrays. It merges the elements of one or more arrays into a single array. If you pass multiple arrays to it, they will be merged sequentially, and any numeric keys will be re-indexed. For example:

$a = [1, 2, 3];
$b = [4, 5, 6];
$c = array_merge($a, $b); // $c = [1, 2, 3, 4, 5, 6]

But what happens when you pass arrays inside an array, like this?

$names = [['John', 'Jane'], ['Mike', 'Alice']];

In this case, using array_merge directly would not work because it's expecting individual arrays as arguments, not an array of arrays. This is where the "spread" operator (...) comes in.

What does the spread operator (...) do?

The spread operator in PHP, represented by ..., is a syntactic sugar introduced in PHP 5.6. It unpacks an array into individual arguments. So, instead of passing the array $names directly, which contains multiple arrays inside it, the spread operator will unpack the arrays within $names and pass them as separate arguments to array_merge.

For example:

$names = [['John', 'Jane'], ['Mike', 'Alice']];
$merged = array_merge(...$names);

The line array_merge(...$names) effectively becomes:

$merged = array_merge(['John', 'Jane'], ['Mike', 'Alice']);

This results in:

$merged = ['John', 'Jane', 'Mike', 'Alice'];

Why use array_merge(...$names)?

You might wonder, why not just merge the arrays manually or in a loop? The answer lies in simplicity and performance. The spread operator combined with array_merge allows you to quickly and cleanly combine multiple arrays in one step, rather than looping through them or using nested merges. It's particularly useful when you have a dynamic number of arrays or when the number of arrays is not known beforehand.

For example, if you have:

$names = [
    ['Anna', 'Bob'],
    ['Charlie', 'David'],
    ['Eve', 'Frank']
];

Using array_merge(...$names) gives you:

['Anna', 'Bob', 'Charlie', 'David', 'Eve', 'Frank']

without any need for extra code.

Points to Remember

  • The spread operator (...) is used to unpack arrays in PHP. It takes an array of arrays and spreads them out as individual arguments for the function.
  • array_merge re-indexes any numeric keys, but preserves associative keys. So, if you're dealing with associative arrays, the behavior might differ. For example:
$a = ['name' => 'John'];
$b = ['age' => 30];
$c = array_merge($a, $b); // ['name' => 'John', 'age' => 30]
  • This technique is especially helpful when you have multiple arrays nested inside another array and want to flatten them into a single array.

Other Use Cases

Beyond merging arrays, the spread operator can be used in function calls as well. For instance, if you have an array of arguments and want to pass them as individual parameters to a function, the spread operator can help:

function greet($name, $age) {
    return "Hello, my name is $name and I am $age years old.";
}

$args = ['John', 25];
echo greet(...$args); // Output: Hello, my name is John and I am 25 years old.

This flexibility allows you to work with dynamic data in a clean and efficient manner.

Finally

The line $names = array_merge(...$names); might seem complex at first, but it's actually a concise way to combine multiple arrays into one. The spread operator (...) unpacks arrays, and array_merge does the heavy lifting of merging them. This approach saves time, reduces code complexity, and can be a handy tool in your PHP toolkit.

As you dive deeper into PHP, you'll find this technique useful in many situations where arrays need to be combined dynamically. Mastering this small trick can make your code more efficient and elegant, helping you write cleaner solutions in your projects.

Support Us

Subscribe to Buka Corner

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe