Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Unpacking inside arrays using spread operator in PHP

If you’ve ever worked with JavaScript, you might be well aware of this feature. So basically, from PHP 7.4, you would be able to unpack arrays into another array using spread operator [...].

Pre PHP 7.4, if you want to merge two arrays, you would need to use methods like array_merge. Take this for example.

<?php
// Pre PHP 7.4

$array = ['foo', 'bar'];

$result = array_merge($array, ['baz']);

print_r($result);
// Array([0] => baz [1] => foo [2] => bar)

But from PHP 7.4, you can achieve above using following syntax:

<?php
// From PHP 7.4

$array = ['foo', 'bar'];

$result = ['baz', ...$array];

print_r($result);
// Array([0] => baz [1] => foo [2] => bar)

You can even unpack multiple arrays into a single array which is not possible using methods such as array_merge as the method like these can only take two arrays at a time.

You may like: Array unpacking with string keys coming in PHP 8.1

Caveat

There’s one issue however with this implementation. And that is you can not unpack the associative arrays. Doing so will throw a fatal error.

So, if we modify the above example into using an associative array and run it…

<?php

$array = ['foo' => 'pikachu', 'bar' => 'pokemon'];

$result = ['baz', ...$array];

print_r($result);

…It will halt the script with the following fatal error.

<b>Fatal error</b>:  Uncaught Error: Cannot unpack array with string keys in [...][...]:6

So, you would need to keep this in mind while using the spread operator. At least, for now. But I’m pretty sure a workaround for this issue will be there in the upcoming versions of PHP.

Finger crossed!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?