PHP 7.4 new syntax: array extension operator

PHP 7.4 new syntax: array extension operator


The RFC vote for Spread Operator support in array expressions is that the vast majority of people agree to add this feature to PHP 7.4.


The expansion operator support parameter unpacking first existed in PHP 5.6, and this RFC expanded the use of arrays; the expansion can support Traversable arrays and objects. This is a basic example of RFC:


$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
//['banana', 'orange', 'apple', 'pear', 'watermelon'];

 

Here is a further example:

$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 explained the key support as follows:

To make the behavior consistent with argument unpacking , string keys are not supported. After encountering a string key, a recoverable error will be thrown.


For more learning content, please visit:

Yae Sakura: How to become an architect from a code farmer must-see knowledge points: Catalog (updated from time to time)
zhuanlan.zhihu.com

The above content hopes to help everyone. Many PHPers always encounter some problems and bottlenecks when they are advanced. There is no sense of direction when writing too much business code. I don t know where to start to improve. I have compiled some information about this, including But not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx, etc. Multiple knowledge points, advanced advanced dry goods, can be shared with everyone for free , and those who need can join my official group click here .