RE: [PHP-DEV] Feature request - allow to append multiple elements to an array
| From: | Iván Arias | Date: | Mon, 30 Mar 2020 00:05:41 +0000 |
| Subject: | RE: [PHP-DEV] Feature request - allow to append multiple elements to an array | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109441@lists.php.net to get a copy of this message | ||
>> $arr[] = 1, 2, 3; // push these 3 values
>> $arr[] = 1, 2, ... [3, 4, 5], 6; // push these 6 values
>
>Just to play with this... - normally an assignment evaluates to the
>value being assigned:
>
>var_dump($arr[] = 1); // int(1)
>
>What would this produce?
>
>var_dump($arr[] = 1, 2, 3);
>
>The first value, an array with 3 values or the full $arr?
Good point there, thanks!
Although I not a big fan on assigning values when calling functions it is a valid syntax, and I
agree that introducing ambiguity does not make any sense.
I think these are actually the options to append multiple items to an array:
1. array_push($arr, 1, 2, 3);
2. $arr = […$arr, 1, 2, 3);
3. foreach ([1, 2, 3] as $i) {
$arr[] = $i;
}
4. foreach ([1,2,3] as $arr[]); // a bit weird, but it does work for php 5.4+[1]
I personally would go with the 2nd if posible, 1st for compatibility, but maybe it could be a bit
less redundant with the David’s proposed syntax:
$arr[] = …[1, 2, 3];
I wonder if it will even better in terms of performance…
[1] https://3v4l.org/7rbiX
Regards,
Iván Arias.