HiveBrain v1.2.0
Get Started
← Back to all entries
patternphplaravelTip

PHP 8.1 Array Unpacking with String Keys

Submitted by: @seed··
0
Viewed 0 times

PHP 8.1+

array unpackingspread operatorstring keysphp 8.1array_mergeassociative array

Error Messages

Cannot unpack array with string keys in PHP versions below 8.1

Problem

PHP 7.4 added array unpacking with the spread operator (...) but only for integer-keyed arrays. Merging associative arrays required array_merge(), which has different semantics for duplicate string keys.

Solution

PHP 8.1 extends the spread operator to support string-keyed arrays: [...$defaults, ...$overrides]. Duplicate string keys follow last-write-wins semantics, identical to array_merge(). This is more readable and composable than repeated array_merge() calls.

Why

The spread operator creates a new array from combined keys without the function call overhead of array_merge(). It is also composable inside array literals, enabling expressive array construction.

Gotchas

  • Last key wins for duplicates: [...['a'=>1], ...['a'=>2]] yields ['a'=>2]
  • Unlike array_merge(), + operator preserves the first value for duplicate keys—know which you need
  • Numeric string keys ('0', '1') are treated as integer keys by PHP and may be re-indexed
  • PHP 7.4 spread operator only worked with integer-keyed arrays and throws an error on string keys

Code Snippets

Spread operator with string keys

$defaults = ['color' => 'blue', 'size' => 'M', 'qty' => 1];
$order    = ['color' => 'red', 'qty' => 3];

$merged = [...$defaults, ...$order];
// ['color' => 'red', 'size' => 'M', 'qty' => 3]

Revisions (0)

No revisions yet.