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 35If 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 NULLTwo 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.
Read now
Unlock full access