Page 158 - Open Soource Technologies 304.indd
P. 158
Web Technologies-I
Notes 7.2 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. Here’s an example:
$person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘Riya’); list($n, $a, $w) = $person; //
$n is ‘Pradip’, $a is 35, $w is ‘Riya’
If you have more values in the array than in the list ( ), the extra values are ignored:
$person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘Riya’); list($n, $a) = $person; // $n
is ‘Pradip’, $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’
7.2.1 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 numeric keys starting at 0. For example:
$people = array (‘Tom’, ‘Dick’, ‘Harriet’, ‘Brenda’, ‘Jo’); $middle = array_slice($people, 2, 2); //
$middle is array(‘Harriet’, ‘Brenda’)
It is generally only meaningful to use array_slice( ) on indexed arrays (i.e., those with consecutive
integer indexes, starting at 0):
// this use of array_slice( ) makes no sense $person = array(‘name’ => ‘Pradip’, ‘age’ => 35,
‘wife’ => ‘Riya’); $subset = array_slice($person, 1, 2); // $subset is array(0 => 35, 1 => ‘Riya’)
Combine array_slice( ) with list( ) to extract only some values to variables:
$order = array(‘Tom’, ‘Dick’, ‘Harriet’, ‘Brenda’, ‘Jo’); list($second, $third) = array_slice($order,
1, 2); // $second is ‘Dick’, $third is ‘Harriet’
7.2.2 Splitting an Array into Chunks
To divide an array into smaller, evenly sized arrays, use the array_chunk( ) function:
$chunks = array_chunk(array, size [, preserve_keys]);
The function returns an array of the smaller arrays. The third argument, preserve_keys, is a
Boolean value that determines whether the elements of the new arrays have the same keys as
in the original (useful for associative arrays) or new numeric keys starting from 0 (useful for
indexed arrays). The default is to assign new keys, as shown here:
152 LOVELY PROFESSIONAL UNIVERSITY