43

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

在 JavaScript 中,您可以使用扩展语法来执行操作:

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

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

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

导致此错误:

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

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

4

4 回答 4

51

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.

于 2019-05-10T07:29:03.867 回答
16
于 2017-07-31T15:44:36.863 回答
6

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'];
于 2019-04-24T15:00:49.647 回答
5

Below 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

$mainArray = ['element1', 'element2'];
$finalArray = [...$mainArray, 'element3'];
print_r($finalArray);
// Final array would be ['element1', 'element2', 'element3'];
于 2020-05-27T06:40:15.897 回答