On 05/11/2014 11:43, Chris Wright wrote:
On 5 November 2014 11:22, Leigh <lei...@gmail.com <mailto:lei...@gmail.com>> wrote:

    On 4 November 2014 18:14, Rowan Collins <rowan.coll...@gmail.com
    <mailto:rowan.coll...@gmail.com>> wrote:
    >
    > If anything, I think I would expect the keys of splatted arrays to be 
discarded, since it
    seems 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

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];


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]


--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to