-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Closed as not planned
Description
Description
Currently spread operator can be used for almost anything. But not for array append.
I propose the following to be supported:
<?php
$arr2 = [3, 'b' => 4];
$arr = [1, 'a' => 2];
$arr[...] = $arr2;
print_r($arr);
// should be the same as - slow, array is copied
$arr = [1, 'a' => 2];
$arr = array_merge($arr, $arr2);
print_r($arr);
// should be the same as - slow, array is copied
$arr = [1, 'a' => 2];
$arr = [...$arr, ...$arr2];
print_r($arr);
// should be the same as - fast, but code is long
$arr = [1, 'a' => 2];
foreach ($arr2 as $k => $v) {
if (is_int($k)) {
$arr[] = $v;
} else {
$arr[$k] = $v;
}
}
print_r($arr);
// array_push() does not accept unknown named parameters
// https://github.com/php/php-src/issues/11026
$arr = [1, 'a' => 2];
array_push($arr, ...$arr2);
Currently the best alternative is array_push
but for single value the man [1] says:
If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.
So the same applies for more elements (discussed in #9881) and having native spread array append would be faster and consitent with other spread language syntax.
The return value of $var[...] = expr
should be the expr
to be consistent with $var[] = expr
- https://3v4l.org/iAK4U.
DRSDavidSoft