PHP 8.1 – Support of merging string keys via Spread Operator

PHP 8.1 – Support of merging string keys via Spread Operator

dragon ball fusion, songo, vegeta, merging strings

Start merging arrays without array_merge() completely. Spread Operator have now a support of integer types of keys, as well as string types keys. So you can merge your arrays more safe than before. Merge away!

This change will follow the semantics of the array_merge() function:

$array = [...$array1, ...$array2];
//same as:
$array = array_merge($array1, $array2);

In particular this means that later string keys overwrite earlier ones:

$array1 = ["a" => 1];
$array2 = ["a" => 2];
$array = ["a" => 0, ...$array1, ...$array2];
var_dump($array); // ["a" => 2]

In this case, the key "a" occurs three times and the last occurrence with value 2 wins.

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment