数组声明中的 PHP 扩展语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45419150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:06:56  来源:igfitidea点击:

PHP Spread Syntax in Array Declaration

phparraysvariadic-functionsspread-syntax

提问by Nathan Arthur

PHP supports the spread syntax for variadic functions.

PHP 支持可变参数函数的扩展语法。

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

在 JavaScript 中,您可以使用 spread 语法来执行此操作

var a = [1, 2];
var b = [...a, 3, 4];
console.log(b); // [1, 2, 3, 4]

However, trying to do this in PHP:

但是,尝试在 PHP 中执行此操作:

$a = [1, 2];
$b = [...$a, 3, 4];
var_dump($b);die;

Results in this error:

导致此错误:

Parse error: syntax error, unexpected '...' (T_ELLIPSIS), expecting ']'

解析错误:语法错误,意外的“...”(T_ELLIPSIS),期待“]”

Is using the spread syntax this way not allowed in PHP? If so, is there an equally-as-elegant way to achieve the same effect?

PHP 中不允许以这种方式使用扩展语法吗?如果是这样,是否有同样优雅的方式来达到相同的效果?

采纳答案by Erald Karakashi

The spread operator in the arrays RFChas been implemented in PHP 7.4:

数组 RFC 中的扩展运算符已在 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.

警告:解包的数组/Traversable 只能有整数键。对于字符串键array_merge()仍然是必需的。

回答by Ravinder Payal

Update: Spread Operator in Array Expression

更新:数组表达式中的扩展运算符

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

来源https: //wiki.php.net/rfc/spread_operator_for_array

Version: 0.2
Date: 2018-10-13
Author: CHU Zhaowei, [email protected]
Status: Implemented (in PHP 7.4)
Version: 0.2
Date: 2018-10-13
Author: CHU Zhaowei, [email protected]
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.

以 为前缀的数组对将在数组定义期间在某些地方展开。只能扩展实现 Traversable 的数组和对象。

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([]).

展开运算符适用于数组语法(array()) 和短语法([])。

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.

首先,您以错误的方式引用带有数组的 Variadic 函数。

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

您可以创建自己的方法来执行此操作,或者您可以更好地使用array_merge@Mark Ba​​ker 在您的问题下的评论中的建议。

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

如果你仍然想使用扩展运算符 / ...,你可以自己实现这样的东西。

<?php
function 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.

但对我来说,这样做是愚蠢的。因为您仍然必须使用诸如 array_merge 之类的东西。即使一种语言实现了这一点,在幕后,该语言也在使用合并函数,该函数包含用于将两个数组的所有元素复制到单个数组中的代码。我写这个答案只是因为你问了这样做的方式,优雅是你的要求。

More reasonable example:

更合理的例子:

<?php
$a = [1,2,3,56,564];
$result = merge($a, 332, 232, 5434, 65);
var_dump($result);
?>

回答by Mwthreex

In PHP 7.4 you can now use Spread Operators in array expressions.

在 PHP 7.4 中,您现在可以在数组表达式中使用扩展运算符。

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

回答by Vivek Maru

Below PHP 7.4

PHP 7.4 以下

$mainArray = ['element1', 'element2'];
$finalArray = array_merge($mainArray, ['element3']);
print_r($finalArray);
// Final array would be ['element1', 'element2', 'element3'];

In or Above PHP 7.4

PHP 7.4 或以上

$mainArray = ['element1', 'element2'];
$finalArray = [...$mainArray, 'element3'];
print_r($finalArray);
// Final array would be ['element1', 'element2', 'element3'];