PHP Keywords: list()

19 February 2019 - 6:57am

Welcome to my series on every PHP keyword and its usage. Today's item: list().

The list() construct simplifies extracting variables from an array, allowing you to assign several variables to values in an array using one statement.

Usage

Basic extraction

<?php
$coordinate = [37, 12];
list($x, $y) = $coordinate;

Note: The list of variables to extract can be shorter than the number of items in the array, it will just ignore any further items. However, the list should not be longer, as it will be treated as trying to reference a non-existent array index.

Nested

<?php
$location = ["Home", [37, 12]];
list($name, list($x, $y)) = $location;

In a loop

<?php
$coordinates =
[
    [37, 12],
    [49, 37],
    [18, 12]
];

foreach($coordinates as list($x, $y))
{
    echo $x, ",", $y, "\n";
}

Into an array

<?php
$coordinate = [37, 12];
$reversedCoordinate = [];
list($reversedCoordinate[1], $reversedCoordinate[0]) = $coordinate;

Using keys/indexes

<?php
$coordinate = [37, 12];

$labelledCoordinate =
[
    "x" => 37,
    "y" => 12
];

list(1 => $y, 0 => $x) = $coordinate;
list("y" => $y, "x" => $x) = $labelledCoordinate;