PHP Spread Syntax in Array Declaration

后端 未结 4 918
遇见更好的自我
遇见更好的自我 2020-12-14 15:40

PHP supports the spread syntax for variadic functions.

In JavaScript, you can use the spread syntax to do this:

var a = [1, 2];
var b = [...a, 3, 4];         


        
4条回答
  •  不知归路
    2020-12-14 15:58

    Update: Spread Operator in Array Expression

    Source: https://wiki.php.net/rfc/spread_operator_for_array

    Version: 0.2
    Date: 2018-10-13
    Author: CHU Zhaowei, jhdxr@php.net
    Status: Implemented (in PHP 7.4)
    

    An array pair prefixed by will be expanded in places during array definition. Only arrays and objects who implement Traversable can be expanded.

    For example:

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

    It's possible to do the expansion multiple times, and unlike argument unpacking, … can be used anywhere. It's possible to add normal elements before or after the spread operator.

    Spread operator works for both array syntax(array()) and short syntax([]).

    It's also possible to unpack array returned by a function immediately.

    $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]
    

    <---------------End of Update-------------------->

    First of all you are referencing the Variadic function with arrays in wrong sense.

    You can create your own method for doing this, or you can better use array_merge as suggested by @Mark Baker in comment under your question.

    If you still want to use spread operator / ..., you can implement something like this yourself.

    
    

    But to me, doing it like this is stupidity. Because you still have to use something like array_merge. Even if a language implements this, behind the scene the language is using merge function which contains code for copying all the elements of two arrays into a single array. I wrote this answer just because you asked way of doing this, and elegancy was your demand.

    More reasonable example:

    
    

提交回复
热议问题