PHP 8.1 : Array unpacking with string keys
12, September 2021

From PHP 7.4, we have array spread/unpack operator that works with arrays with integer keys. At that time, argument unpacking didn't support string keys too, so array unpack functionality was consistent with it. But on PHP 8.0, argument unpacking started supporting string keys too via Named Parameters. Now PHP 8.1 enables us to unpack regular arrays with string keys too. YAY!


Regular arrays with no duplicate keys just gets appended.

$arr1 = ['a' => 1, 'c' => 3];
$arr2 = ['b' => 2, 'd' => 4];

print_r([...$arr1, ...$arr2]);
// Array(
//    [a] => 1
//    [c] => 3
//    [b] => 2
//    [d] => 4
//)


If there are any duplicate keys, the last key wins the race:

$arr1 = ['a' => 1, 'b' => 3];
$arr2 = ['b' => 2, 'd' => 4];

print_r([...$arr1, ...$arr2]);
//Array(
//    [a] => 1
//    [b] => 2
//    [d] => 4
//)

Notice how 'b' => 3 got replaced by 'b' => 2 because it came later.

Numeric keys are always appended, even if they are stringly typed:

$arr1 = ['1' => 1, '2' => 3];
$arr2 = ['2' => 2, '4' => 4];

print_r([...$arr1, ...$arr2]);
//Array(
//    [0] => 1
//    [1] => 3
//    [2] => 2
//    [3] => 4
//)


We can mix arrays with string and numeric keys too:

$arr1 = ['a' => 1, 3];
$arr2 = [2, 'b' => 4];

print_r([...$arr1, ...$arr2]);
//Array(
//    [a] => 1
//    [0] => 3
//    [1] => 2
//    [b] => 4
//)

Notice how string keys are preserved.


Also, the behavior is fully compatible with array_merge(), so we can switch between these two as we prefer.


RFC: https://wiki.php.net/rfc/array_unpacking_string_keys


Write comment about this article: