Spread Operator for Arrays Coming to PHP 7.4

Spread Operator for Arrays

The RFC vote for spread operator support in Array expressions was overwhelmingly in favor of adding this feature to PHP 7.4.

The spread operator support for argument unpacking first existed in PHP 5.6, and this RFC expands on the usage to arrays; both arrays and objects that support Traversable can be expanded. Here’s a basic example from the RFC:

$parts = ['charlie', 'zulu'];
$fruits = ['alpha', 'mike', ...$parts, 'dude'];
// ['alpha', 'mike', 'charlie', 'zulu', 'watermelon'];

Here are some further examples:

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; // [1, 2, 3]
$arr3 = [0, ...$arr1]; // [0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); // [1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; // [1, 2, 3, 1, 2, 3]

function getArr() {
  return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; // ['a', 'b', 'c']

$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; // ['a', 'b', 'c']

function arrGen() {
    for($i = 11; $i < 15; $i++) {
        yield $i;
    }
}
$arr8 = [...arrGen()]; // [11, 12, 13, 14]

String keys are not supported; you can only use indexed arrays. The author of the RFC explains key support as follows:

In order to make the behavior consistent with argument unpacking , string keys are not supported. A recoverable error will be thrown once a string key is encountered.

Related: PHP Approves Short Arrow Functions

To learn about the full details of this accepted proposal, check out the PHP: rfc:spread_operator_for_array. We want to thank CHU Zhaowei for writing this RFC (and everyone involved). We think it’s going to be an excellent addition to PHP!

Tags: website development company in delhi|| website designing company in delhi || b2b portal development company || magento development company in delhi ||  website redesigning company in delhi

About Post Author