The RFC vote for Spread Operator support in array expressions is Overwhelmingly in favor Add this feature to PHP 7.4.
Extension operator support for parameter unpacking first existed in PHP 5.6, and this RFC extends the use of arrays; the extension can support Traversable arrays and objects. Here is a basic example from the RFC:
$parts = ['apple', 'pear']; $fruits = ['banana', 'orange', ...$parts, 'watermelon']; // ['banana', 'orange', 'apple', 'pear', 'watermelon'];
Here are 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 states the following about key support:
To keep behavior consistent with argument unpacking, string keys are not supported. A recoverable error will be thrown after a string key is encountered.
For more PHP related technical articles, please visit the PHP Tutorial column to learn!
The above is the detailed content of PHP 7.4 new syntax: array spread operator. For more information, please follow other related articles on the PHP Chinese website!