Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

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('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a, $w) = $person;            // $n is 'Fred', $a is 35, $w is 'Betty'

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

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a) = $person;                // $n is 'Fred', $a 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');
list($m,,$n,,$o) = $values;            // $m is 'a', $n is 'c', $o is 'e'

Slicing an Array

To extract only a subset of the array, use the array_slice( ) function:

$subset = array_slice(array, offset, length);

The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array. The offset parameter identifies the initial element to copy (0 represents the first element in the array), and the length parameter identifies the number of values to copy. The new array has ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata