Re: Suggestion: Inconsistency: Allow array spread operator to work on string keys
| From: | Christian Schneider | Date: | Wed, 02 Dec 2020 21:19:38 +0000 |
| Subject: | Re: Suggestion: Inconsistency: Allow array spread operator to work on string keys | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112384@lists.php.net to get a copy of this message | ||
Am 02.12.2020 um 18:24 schrieb Florian Stascheck <florian.stascheck@gmail.com>:
> I suggest to allow string keys to also be used in array literals:
>
> $template = ['created_at' => time(), 'is_admin' => 1];
> $db_rows = [
> ['name' => 'Alice', 'email' =>
> 'alice@example.org', ....$template],
> ['name' => 'Bob', 'email' => 'bob@example.org',
> ...$template],
> ];
You can already easily enough do this with
$db_rows = [
['name' => 'Alice', 'email' => 'alice@example.org']
+ $template,
['name' => 'Bob', 'email' => 'bob@example.org']
+ $template,
];
so I'm not sure if it is really needed.
But then again I'm used to the +-operator for associative arrays and wouldn't expect to be
able to use the spread operator instead. Someone learning PHP now might see things differently.
Side-note:
For the ...$template syntax I would assume that later values win (like ['foo' =>
"bar", 'foo' => "qux"] will result in ['foo' =>
"qux"]) so the exact equivalent for your example would probably be
$template + ['name' => 'Alice', 'email' =>
'alice@example.org'],
but in reality one often wants to be able to override template values, that's why I wrote [ ...
] + $template and your example would be
[...$template, 'name' => 'Alice', 'email' =>
'alice@example.org'],
- Chris