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

1
2
3
<?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

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

In a loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
$coordinates =
[
	[37, 12],
	[49, 37],
	[18, 12]
];

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

Into an array

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

Using keys/indexes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
$coordinate = [37, 12];

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

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