PHP 8.1: Array unpacking support for string-keyed arrays

Version8.1
TypeNew Feature

Since PHP 7.4, PHP supports array spread operator ( ...) for array unpacking. An array can be unpacked with another array if the array expression is prefixed with the spread operator. This effectively results in an array_merge of all arrays in the expression.

$array_1 = ['foo', 'bar'];
$array_2 = ['baz', 'qux'];

$array_unpacked = [...$array_1, ...$array_2, ...['quux']];
$array_merged   = array_merge($array_1, $array_2, ['quux']);

var_dump($array_unpacked);
// ['foo', 'bar', 'baz', 'qux', 'quux'];

var_dump($array_merged);
// ['foo', 'bar', 'baz', 'qux', 'quux'];

array_merge function merges all gives arrays in the order they are passed. Arrays with numeric keys will appended and renumbered, and duplicate string keys will be overwritten with later values.

Prior to PHP 8.1, the spread operator only supported arrays with numeric keys. Using an array with string key resulted in an error prior to PHP 8.1:

$array = [...['a' => 'foo'], ...['b' => 'bar']];
Fatal error: Cannot unpack array with string keys in ... on line ...

From PHP 8.1, array unpacking supports arrays with string keys as well.

$array = [...['a' => 'foo'], ...['b' => 'bar']];
// ['a' => 'foo', 'b' => 'bar'];

Array Unpacking vs array_merge

Array unpacking and array_merge results in identical values.

$array_unpack = [
    ...['a' => 'foo'], 
    ...['b' => 'bar'],
    ...['c' => 'baz']
];
$array_merge = array_merge(
    ['a' => 'foo'],
    ['b' => 'bar'],
    ['c' => 'baz'],
);

$array_unpack === $array_merge; // true

Array Unpacking vs + operator

Array unpacking overwrites duplicate string keys, while the + operator ignores duplicate string keys.

var_dump(
     ['a' => 'foo']
    +['a' => 'bar']
);
// ['a' => 'foo'];

var_dump([
     ...['a' => 'foo'],
     ...['a' => 'bar']
]);
// ['a' => 'bar'];

Backwards Compatibility Impact

The array unpacking operator did not support string-keys prior to PHP 8.1, and resulted in a fatal error. Existing code that runs successfully on older versions should not cause any issues in PHP 8.1 or later.

array_merge results in identical results in all PHP versions. array_merge , and should be used on code that requires compatibility with PHP versions prior to 8.1.


RFC Discussion Implementation