Array Unpacking with String Keys in PHP 8.1

Array Unpacking with String Keys in PHP 8.1

PHP has spread operator (...) which allows unpacking arrays. When array is prefixed with spread operator, an array elements are spread in place. The spread operator can be used multiple times.

<?php

$array1 = ['red', 'green'];
$array2 = ['blue', 'gray'];
$array = [...$array1, ...$array2, ...['orange']];

print_r($array); // ([0] => red [1] => green [2] => blue [3] => gray [4] => orange)

In versions prior to PHP 8.1, the spread operator can be used only for arrays with numeric keys. Using an array with string keys, PHP results a fatal error.

Since PHP 8.1, the spread operator can be used to unpack an array with string keys.

<?php

$array1 = ['a' => 'red', 'b' => 'green'];
$array = [...$array1, ...['c' => 'blue']];

print_r($array); // ([a] => red [b] => green [c] => blue)

The spread operator uses the same rules as the array_merge function when merging two arrays with duplicate keys. Arrays are merged in the order they are passed, and numeric keys are renumbered.

<?php

$array1 = [2 => 'red', 4 => 'green'];
$array2 = [1 => 'blue', 2 => 'gray'];
$array = [...$array1, ...$array2];

print_r($array); // ([0] => red [1] => green [2] => blue [3] => gray)

Arrays which contains duplicate string keys will be overwritten with later values.

<?php

$array1 = ['c' => 'red', 'b' => 'green'];
$array2 = ['a' => 'blue', 'c' => 'gray'];
$array = [...$array1, ...$array2];

print_r($array); // ([c] => gray [b] => green [a] => blue)

Leave a Comment

Cancel reply

Your email address will not be published.