Spread Operator for Arrays Coming to PHP 7.4

Spread Operator for Arrays Coming to PHP 7.4

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 = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', '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!

Filed in: News / php7.4
Laravel News Partners

Laravel Jobs

Web Application Developer (Vue.js & Laravel)
Remote
Apero Creative Development
Full Stack PHP Engineer
Alexandria, VA
Engage, LLC
Mid / Senior Laravel / Vue Engineer
Clearwater, FL
ShineOn
Platform Engineer
Canada
Maple
Intermediate Laravel Developer
Austin, TX
Elevation Energy Group

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.