Table of Contents

PHP RFC: Short Array Variable Shorthand

Introduction

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
?>

Proposal

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.

Examples

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
?>

Backward Incompatible Changes

None. The proposed syntax is currently invalid.

Proposed PHP Version(s)

PHP 8.7.

RFC Impact

To the Ecosystem

Static analyzers must recognize the new [] element form.

To Existing Extensions

None.

To SAPIs

None.

Open Issues

None.

Future Scope

The long array() and list() forms, and shorthand in function calls, are outside this RFC.

Voting Choices

TBD. Not in the voting process.

Patches and Tests

TBD.

Implementation

TBD.

References

Rejected Features

None.

Changelog