Re: Suggestion: Inconsistency: Allow array spread operator to work on string keys

From: Date: Wed, 02 Dec 2020 17:45:47 +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-112379@lists.php.net to get a copy of this message
On Wed, 2 Dec 2020 at 17:24, Florian Stascheck <florian.stascheck@gmail.com> wrote: > Hello! > > With PHP8 released and the named arguments RFC being implemented, there's > now an inconsistency in how the spread operator works. > > Historically, the spread operator was first used in PHP 5.6 for arguments: > > function php56($a, $b) { > return $a + $b; > } > $test = [1, 2]; > php56(...$test) === 3; > > Then, with PHP 7.4, the spread operator was also introduced for array > literal syntax: > > $parts = ['apple', 'banana']; > $fruits = ['strawberry', ...$parts, 'grape']; > $fruits == ['strawberry', 'apple', 'banana', 'grape']; > > The RFC back then explicitly excluded [1] string keys, to make the > functioning of the spread operator consistent with how it's used for > function arguments. > > Now, in PHP8 we can do: > > function php8(int $a, int $b): int { > return $a + $b; > } > $test = ['b' => 40, 'a' => 2]; > php8(...$test) === 42; > > However, string keys in array literals are still not possible. So the > limitation that once was introduced for consistency now led to an > inconsistency. > > 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], > ]; > > What's your feedback on that? Do you see any obvious problems with that > approach? I searched through the archives and couldn't find this problem > being mentioned before. > > -Florian > > [1]: > https://wiki.php.net/rfc/spread_operator_for_array#string_keys The reason why this has been deferred is because of which semantics should be used for duplicate string keys. Do we use the addition between two arrays semantics or the array_merge() semantics? See: https://3v4l.org/7QbWv As the previous RFC you linked initially wanted to use the array_merge() semantics. But due to contention was left out. Best regards, George P. Banyard

« previous php.internals (#112379) next »