Re: [RFC] Spread Operator in Array Expression

php.internals

=?utf-8?B?5rGf5rmW5aSn6Jm+5LuB?=

7 years ago
> Hi, I worked together with Chris Wright, author of the other RFC covering > the same thing.
Thanks for pointing it out and also thanks CMB for posting the link. I tried to search for this topic but didn't find anything, as we have too many names for this feature.
> The most important thing is that we don't want it work like array_merge(); > in other words, it must not cover both lists and maps at the same time.
Since PHP array is a mixture of list (traditional array in most of other languages) and map (a k=>v data structure), any new syntax related to PHP array most cover both use cases. `...` means unpacking, I think we are all good with this semantic, the disagreement is about the behavior of key conflict. Let's use your example to start my explanation: ``` ['a' => 1, 'b'=>2, ...['a' => 3]] ``` Since we are create a new syntax with the existing array definition syntax, let's try to do the unpack manually. ``` ['a' => 1, 'b' =>2, 'a' => 3] ``` Although this not a good practice to write such codes, it's still valid in current version without any warning or even notice. The answer for above code is ``` ['a' => 3, 'b' => 2] ``` It looks weird at first glance, but IMO the more important thing is this is how PHP works now. I really don't think it's a good idea to introduce a new way how two arrays will get merged. It will confuse developers. I also notice there is an interesting question in the discussion of your RFC.
> So, it's just an operator version of array_merge(), with no advantages > other than brevity? I'm not sure why it's any more or less applicable to > constant arrays vs variables than + or array_merge() are.
Yes. The spread operator follows the semantics as `array_merge`, but besides brevity and better performance (no more overhead of function call, and constant array can be compiled at compiled time), this RFC also brings the support for objects implementing `Traversables`. Best regards, CHU Zhaowei

Net Mo

7 years ago
Maybe I wasn't clear enough the first time. If you want to merge two maps, you use $a + $b. This functionality already exist. The missing functionality is push / unshift and concat. (And if you really want it, the previously mentioned "ordered map concat" behavior)