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'

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
    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 consecutive ...

Get Programming PHP, 2nd 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.