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


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Remote PHP / Laravel Developer
Remote
SpringboardVR
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Laravel Developer
Leidseplein, Amsterdam
Orderchamp.com
PHP Developer
Remote
X-Team
Senior Laravel Developer (Canada and India)
London, Ontario, Canada
Factory Bucket Inc.
Laravel, PHP, PostgreSQL, Neo4J Developer
Pune, India (intern in Denver, CO)
Life AI
Senior Laravel Developer - Cloud based SaaS product (New Zealand based)
Auckland city
Figured Limited