Extracting Multiple Values

To copy all of an array’s values into variables, use the list() construct:

list ($variable, ...) = $array;

The array’s values are copied into the listed variables in the array’s internal order. By default that’s the order in which they were inserted, but the sort functions described later let you change that. Here’s an example:

$person = array("Fred", 35, "Betty");
list($name, $age, $wife) = $person;
// $name is "Fred", $age is 35, $wife is "Betty"

Note

The use of the list function is a common practice for picking up values from a database selection where only one row is returned. This would automatically load the data from the simple query into a series of local variables. Here is an example of selecting two opposing teams from a sports scheduling database:

$sql = "SELECT HomeTeam, AwayTeam FROM schedule WHERE Ident = 7";
$result = mysql_query($sql);
list($hometeam, $awayteam) = mysql_fetch_assoc($result);

There is more coverage on databases in Chapter 8.

If you have more values in the array than in the list(), the extra values are ignored:

$person = array("Fred", 35, "Betty");
list($name, $age) = $person;         // $name is "Fred", $age is 35

If you have more values in the list() than in the array, the extra values are set to NULL:

$values = array("hello", "world");
list($a, $b, $c) = $values;          // $a is "hello", $b is "world", $c is NULL

Two or more consecutive commas in the list() skip values in the array:

$values = range('a', 'e');             // use range to populate the array

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.