PHP 7.4 new syntax: array spread operator

步履不停
Release: 2023-02-23 08:44:01
Original
5305 people have browsed it

PHP 7.4 new syntax: array spread operator

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'];
Copy after login

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]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template