Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required