Associative arrays often repeat a key and a variable with the same name. This RFC proposes :$name as shorthand for “name” => $name inside short [] syntax:
<?php $x = 10; $y = 20; $point = [:$x, :$y]; // $point = ['x' => $x, 'y' => $y] [:$x, :$y] = $point; // ['x' => $x, 'y' => $y] = $point ?>
Within [], :$name uses the variable's lexical name as a string key. In an array expression it reads $name; in destructuring it assigns the value at key “name” to $name. Both forms behave exactly like the explicit keyed element, including existing rules for duplicate or missing keys.
The shorthand also works in nested [] and in [] destructuring used by foreach. It accepts only a simple variable. Other values still use an explicit key, for example [“name” => $object->name].
Important: This RFC supports only []. The forms array(:$name) and list(:$name) remain invalid. It does not change function calls.
An array can mix the shorthand with explicit keys:
<?php $name = 'Weilin'; $age = 18; $user = ['id' => 1, :$name, :$age]; // ['id' => 1, 'name' => 'Weilin', 'age' => 18] ?>
The shorthand can also be mixed with explicit keys when destructuring:
<?php $user = ['name' => 'Weilin', 'age' => 18]; [:$name, 'age' => $years] = $user; // $name === 'Weilin'; $years === 18 ?>
Here is an example in a foreach loop:
<?php $rows = [['name' => 'Weilin']]; foreach ($rows as [:$name]) { echo $name; // Weilin } ?>
Nested short-array destructuring works in the same way:
<?php $record = ['user' => ['name' => 'Weilin']]; ['user' => [:$name]] = $record; echo $name; // Weilin ?>
None. The proposed syntax is currently invalid.
PHP 8.7.
Static analyzers must recognize the new [] element form.
None.
None.
None.
The long array() and list() forms, and shorthand in function calls, are outside this RFC.
TBD. Not in the voting process.
TBD.
TBD.
None.