Re: [RFC] Additional splat operator usage
| From: | Rowan Collins | Date: | Fri, 07 Nov 2014 17:49:05 +0000 |
| Subject: | Re: [RFC] Additional splat operator usage | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-78848@lists.php.net to get a copy of this message | ||
On 05/11/2014 11:43, Chris Wright wrote:
On 5 November 2014 11:22, Leigh <leight@gmail.com <mailto:leight@gmail.com>> wrote:Actually, it would be identical to writing: $bar = ['c' => 4, 'd' => 5, 'e' => 6, 'a' => 1, 'b' => 2, 'c' => 3]; http://3v4l.org/4to7v To keep the keys in alphabetical order and have 'c' => 4 in the result, you would need to write: $bar = [...$foo, 'c' => 4, 'd' => 5, 'e' => 6];On 4 November 2014 18:14, Rowan Collins <rowan.collins@gmail.com <mailto:rowan.collins@gmail.com>> wrote:If anything, I think I would expect the keys of splatted arrays to be discarded, since itseems most natural to use this in a list context, but I can imagine always having to check in the manual.I agree on this point. Duplicate keys should not overwrite each other.[...$foo, ...$bar] should literally unpack the values as if they were comma delimited and discard all key information.Here's how I picture this, which is the rationale for my view on how it should behave: $foo = ['a' => 1, 'b' => 2, 'c' => 3]; $bar = ['c' => 4, 'd' => 5, 'e' => 6, ...$foo]; // is identical to writing $bar = ['a' => 1, 'b' => 2, 'c' => 3, 'c' => 4, 'd' => 5, 'e' => 6]; http://3v4l.org/inqtg#v540
In other words, in that scenario it's basically syntactic sugar to avoid having to write out the "body" of the array twice, and would behave identically as if you had done this.There is no need to write anything twice, the + operator gives a very similar result, although it prefers the first of a set of duplicate keys, not the last: $foo = ['a' => 1, 'b' => 2, 'c' => 3]; $bar = $foo + ['c' => 4, 'd' => 5, 'e' => 6]; // keys in alphabetical order, keeps 'c' => 3 // http://3v4l.org/Vri8j $foo = ['a' => 1, 'b' => 2, 'c' => 3]; |$bar = ['c' => 4, 'd' => 5, 'e' => 6] + $foo; | // keeps 'c' => 4, but keys now not in order http://3v4l.org/lDPou Alternatively, array_merge() is in every way identical to what you propose, and still requires no duplication, just a few extra keystrokes to write the function call: $foo = ['a' => 1, 'b' => 2, 'c' => 3]; $bar = array_merge($foo, |['c' => 4, 'd' => 5, 'e' => 6]);| http://3v4l.org/UXZ2s -- Rowan Collins [IMSoP]