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

Amit Merchant

A blog on PHP, JavaScript, and more

Array unpacking with string keys coming in PHP 8.1

The spread operator in PHP is getting more awesome in PHP 8.1!

So, to give you a primer, with the release of PHP 7.4, it got possible to merge multiple arrays by unpacking arrays into another array using spread operator [...]. It was only possible by using methods like array_merge before PHP 7.4.

Here’s how you can merge multiple arrays using array unpacking.

<?php

$foo = ['bar'];
$baz = ['qux'];

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

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

The caveat

There was however one caveat in this. And that is you can not unpack the associative arrays. Doing so will throw a fatal error like so.

<?php

$array1 = ['john' => 'doe'];
$array2 = ['harry' => 'potter'];
$array = [...$array1, ...$array2];
echo "<pre>";
var_dump($array);

// Fatal error: Uncaught Error: Cannot unpack array with 
// string keys in /var/www/index.php:5 
// Stack trace: #0 {main} thrown in /var/www/index.php on line 5

But this is getting solved starting from PHP 8.1!

Array unpacking with string keys

There is this RFC for PHP 8.1 which proposes to permit unpacking of string keys (associative arrays) into arrays as well.

This means that the example we looked at previously would work just fine in PHP 8.1. Take a look.

<?php

$array1 = ['john' => 'doe'];
$array2 = ['harry' => 'potter'];
$array = [...$array1, ...$array2];
echo "<pre>";
var_dump($array);
// ['john' => 'doe', 'harry' => 'potter']

One thing to note here is, if there is a key that occurs several times in the array, in that case, the later string key overwrites the earlier one. Take below for an example.

<?php

$array1 = ['john' => 'doe'];
$array2 = ['john' => 'potter'];
$array = [...$array1, ...$array2];
echo "<pre>";
var_dump($array);
// ['john' => 'potter']

Although the RFC is still in the voting phase, the good news here is almost every voter has given it the “green” signal already.

So, it’s almost certain that the RFC will get implemented in PHP 8.1!


UPDATE: The RFC has been accepted and this feature is now a part of PHP 8.1.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), 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?