list() / Short Array Destructuring
debt(d5/e1/b1/t5)
Closest to 'specialist tool catches it' (d5). The detection_hints list Rector and php-cs-fixer, both specialist/automated tools that can identify the repetitive $arr[0]/$arr[1] pattern and flag or transform it. A standard linter won't catch this by default, but these dedicated tools will.
Closest to 'one-line patch or single-call swap' (e1). The quick_fix explicitly describes replacing repetitive index access with list() or [] syntax — a single-expression swap. No structural changes required.
Closest to 'minimal commitment' (b1). This is a local syntax choice at the assignment site. It touches a single line or expression and imposes no ongoing tax on other parts of the codebase. The tags confirm it is purely a syntax/arrays concern.
Closest to 'notable trap' (t5). The misconception field identifies that list() and [] are not fully interchangeable — list() preserves historical left-to-right assignment order in some edge cases. Additionally, common_mistakes include silently using positional destructuring on associative arrays and missing length checks causing undefined index notices. These are documented gotchas that developers eventually learn, consistent with t5.
Also Known As
TL;DR
Explanation
PHP's list() construct (and its [] shorthand since PHP 7.1) destructures arrays into named variables. PHP 7.1 enabled key-based destructuring (['name' => $name, 'age' => $age] = $row) for associative arrays, greatly improving database row handling. Nested destructuring is supported. list() is especially useful with foreach for unpacking tuple-like arrays: foreach ($rows as [$id, $name]) and for swapping variables: [$a, $b] = [$b, $a]. Accessing a non-existent key emits a notice — validate structure first.
Common Misconception
Why It Matters
Common Mistakes
- Using list() with associative arrays without specifying keys — positional destructuring of associative arrays is error-prone.
- Not checking that the source array has enough elements — undefined index notices on short arrays.
- Confusing list() (assignment) with array() (creation) — similar syntax, completely different purpose.
- Using list() in PHP < 7.1 for associative array destructuring — key-based list() was added in 7.1.
Code Examples
// Positional list() on associative array — order-dependent and fragile:
[$name, $email] = $user; // Relies on array key order — breaks if order changes
// Safe:
['name' => $name, 'email' => $email] = $user; // Explicit key mapping
// list() / [] — destructure arrays into variables
[$first, $second, $third] = [10, 20, 30];
// Skip elements
[, $second] = getCoordinates(); // ignore x, capture y
// Nested
[[$x1, $y1], [$x2, $y2]] = [[1,2],[3,4]];
// Associative (PHP 7.1+)
['name' => $name, 'age' => $age] = $user;
// In foreach — unpack each row
$points = [[1,2,'A'], [3,4,'B']];
foreach ($points as [$x, $y, $label]) {
echo "$label: ($x, $y)\n";
}
// Classic swap without temp variable
[$a, $b] = [$b, $a];