Re: Using Arrays in 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('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'
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 indices starting at 0):
__________________ Thanks & Regards
Sabari... |