How to Use list() for PHP Array Destructuring

This article explains how the list() language construct works in PHP to perform array destructuring. You will learn the fundamental syntax of list(), how to assign array elements to individual variables, how to handle both indexed and associative arrays, and how this construct compares to the modern shorthand [] syntax.

What is list() in PHP?

In PHP, list() is not a function, but a language construct used to assign a list of variables in one operation. It allows you to “unpack” or destructure an array, mapping its nested values directly into distinct variables.

Destructuring Indexed Arrays

The most common use case for list() is extracting values from a numerically indexed array. The variables inside list() are assigned values from the array based on their numerical index, starting from zero.

$info = ['John Doe', 'Developer', 'New York'];

// Destructuring the array
list($name, $profession, $city) = $info;

echo $name;       // Outputs: John Doe
echo $profession; // Outputs: Developer
echo $city;       // Outputs: New York

Skipping Elements

If you only need specific elements from the array, you can skip elements by omitting variables within the list() construct, leaving empty spaces separated by commas.

$info = ['John Doe', 'Developer', 'New York'];

// Extract only the name and city, skipping the profession
list($name, , $city) = $info;

echo $name; // Outputs: John Doe
echo $city; // Outputs: New York

Destructuring Associative Arrays

Starting in PHP 7.1, list() supports destructuring associative arrays by defining explicit keys. This allows you to assign values to variables regardless of the order of the keys in the array.

$user = [
    'id' => 101,
    'username' => 'johndoe',
    'email' => 'john@example.com'
];

// Destructure by specifying keys
list('username' => $userAdmin, 'email' => $userEmail) = $user;

echo $userAdmin; // Outputs: johndoe
echo $userEmail; // Outputs: john@example.com

Nested Array Destructuring

You can nest list() constructs to unpack multidimensional arrays into individual variables in a single statement.

$matrix = [1, [2, 3]];

// Destructuring a nested array
list($a, list($b, $c)) = $matrix;

echo $a; // Outputs: 1
echo $b; // Outputs: 2
echo $c; // Outputs: 3

The Modern Alternative: Shorthand Square Bracket Syntax

PHP 7.1 introduced a shorthand syntax [] that functions identically to list(). It is generally preferred in modern PHP development for its conciseness.

$info = ['John Doe', 'Developer'];

// Shorthand destructuring
[$name, $profession] = $info;

$user = ['id' => 101, 'role' => 'Admin'];

// Shorthand associative destructuring
['role' => $userRole] = $user;

Both list() and the [] syntax achieve the exact same result under the hood. You can choose whichever style fits your codebase best.