PHP Spread Syntax in Array Declaration
The spread operator in the arrays RFC has been implemented in PHP 7.4:
$ary = [3, 4, 5];return [1, 2, ...$ary]; // same as [1, 2, 3, 4, 5]
Caveat: The unpacked array/Traversable can only have integer keys. For string keys array_merge()
is still required.
Update: Spread Operator in Array Expression
Source: https://wiki.php.net/rfc/spread_operator_for_array
Version: 0.2Date: 2018-10-13Author: CHU Zhaowei, jhdxr@php.netStatus: 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.
<?phpfunction merge($a, ...$b) { return array_merge($a,$b);}$a = [1, 2];$b = [3,4];print_r( merge($a, ...$b));?>
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:
<?php$a = [1,2,3,56,564];$result = merge($a, 332, 232, 5434, 65);var_dump($result);?>
In PHP 7.4 you can now use Spread Operators in array expressions.
$parts = ['apple', 'pear'];$fruits = ['banana', 'orange', ...$parts, 'watermelon'];// ['banana', 'orange', 'apple', 'pear', 'watermelon'];