PHP

πŸ“¦ PHP list() Language Construct: Array Destructuring

The list() construct in PHP is used to assign array elements directly to individual variables in a single step.

  • Key Feature: list() is officially a language construct (not a function) primarily used with numerically indexed arrays to write clean, readable code.

πŸ› οΈ Basic Usage & Index Order

Variable assignment occurs sequentially based on the internal index positions of the target array:

PHP
$fruits = ["Apple", "Pear", "Banana"];

// Assign array elements to variables in order
list($a, $b, $c) = $fruits;

echo $a; // Outputs: Apple
echo $b; // Outputs: Pear
echo $c; // Outputs: Banana

🎯 Skipping Elements & Edge Cases

You can extract only specific items by leaving blank commas, or handle missing and extra array values safely:

PHP
$fruits = ["Apple", "Pear", "Banana", "Strawberry"];

// 1. Skip items: Extract only the third element
list(, , $lastFruit) = $fruits;
echo $lastFruit; // Outputs: Banana

// 2. Extra values: "Strawberry" is simply ignored
list($first, $second) = $fruits;

// 3. Missing values: Assigning more variables than array items triggers null/undefined
$shortArray = ["Apple", "Pear"];
list($x, $y, $z) = $shortArray; // $z becomes null (may trigger Warning in strict PHP)

⚑ PHP 7.1+ Short Array Destructuring Syntax

Since PHP 7.1, you can use the concise square bracket notation [...] as a modern replacement for list():

PHP
$data = ["John", "Doe", 30];

// Modern short syntax (PHP 7.1+)
[$firstName, $lastName, $age] = $data;

echo $firstName; // Outputs: John
echo $age;       // Outputs: 30

πŸ“‹ Key Rules & Behaviors

  • 1. Index Order Sensitivity: Assignment strictly depends on array index ordering unless keys are explicitly declared in PHP 7.1+.
  • 2. Language Construct: Works directly within parser grammar without standard function call overhead.
  • 3. Associative Keys: Standard list() expects numeric arrays; use key-based destructuring (["key" => $var]) for associative arrays in PHP 7.1+.

πŸ“Š list() Feature Overview

Feature Description
Primary Purpose Assigns array elements directly to separate variables
Input Type Indexed Array
Output Individual Variables
Order Dependent? βœ… Yes (Matches index sequence)
Modern Syntax [$a, $b] = $array (PHP 7.1+)
  • πŸ“ Short Summary

  • list() quickly converts array positions into dedicated variables.
  • It ignores extra array items and allows skipping specific elements using commas.
  • Modern PHP code favors the concise [$a, $b] = $array destructuring syntax.