Programming PHPProgramming PHPSearch this book

5.5. 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'

5.5.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' => 'Fred', 'age' => 35, 'wife' => 'Betty');
$subset = array_slice($person, 1, 2);  // $subset is array(0 => 35, 1 => 'Betty')

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'

5.5.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:

$nums = range(1, 7);
$rows = array_chunk($nums, 3);
print_r($rows);
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )
    [2] => Array
        (
            [0] => 7
        )
)

5.5.3. Keys and Values

The array_keys( ) function returns an array consisting of only the keys in the array, in internal order:

$array_of_keys = array_keys(array);

Here's an example:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$keys = array_keys($person);      // $keys is array('name', 'age', 'wife')

PHP also provides a (less generally useful) function to retrieve an array of just the values in an array, array_values( ) :

$array_of_values = array_values(array);

As with array_keys( ), the values are returned in the array's internal order:

$values = array_values($person);       // $values is array('Fred', 35, 'Wilma');

5.5.4. Checking Whether an Element Exists

To see if an element exists in the array, use the array_key_exists( ) function:

if (array_key_exists(key, array)) { ... }

The function returns a Boolean value that indicates whether the second argument is a valid key in the array given as the first argument.

It's not sufficient to simply say:

if ($person['name']) { ... }           // this can be misleading

Even if there is an element in the array with the key name, its corresponding value might be false (i.e., 0, NULL, or the empty string). Instead, use array_key_exists( ) as follows:

$person['age'] = 0;                    // unborn?
if ($person['age']) {
  echo "true!\n";
}
if (array_key_exists('age', $person)) {
  echo "exists!\n";
}
exists!

In PHP 4.0.6 and earlier versions, the array_key_exists( ) function was called key_exists( ). The original name is still retained as an alias for the new name.

Many people use the isset( ) function instead, which returns true if the element exists and is not NULL:

$a = array(0,NULL,'');
function tf($v) { return $v ? "T" : "F"; }
for ($i=0; $i < 4; $i++) {
  printf("%d: %s %s\n", $i, tf(isset($a[$i])), tf(array_key_exists($i, $a)));
}
0: T T
1: F T
2: T T
3: F F

5.5.5. Removing and Inserting Elements in an Array

The array_splice( ) function can remove or insert elements in an array:

$removed = array_splice(array, start [, length [, replacement ] ]);

We'll look at array_splice( ) using this array:

$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama', 'classics');

We can remove the math, bio, and cs elements by telling array_splice( ) to start at position 2 and remove 3 elements:

$removed = array_splice($subjects, 2, 3);
// $removed is array('math', 'bio', 'cs')
// $subjects is array('physics', 'chem');

If you omit the length, array_splice( ) removes to the end of the array:

$removed = array_splice($subjects, 2);
// $removed is array('math', 'bio', 'cs', 'drama', 'classics')
// $subjects is array('physics', 'chem');

If you simply want to delete the elements and you don't care about their values, you don't need to assign the results of array_splice( ):

array_splice($subjects, 2);
// $subjects is array('physics', 'chem');

To insert elements where others were removed, use the fourth argument:

$new = array('law', 'business', 'IS');
array_splice($subjects, 4, 3, $new);
// $subjects is array('physics', 'chem', 'math', 'bio', 'law', 'business', 'IS')

The size of the replacement array doesn't have to be the same as the number of elements you delete. The array grows or shrinks as needed:

$new = array('law', 'business', 'IS');
array_splice($subjects, 2, 4, $new);
// $subjects is array('physics', 'chem', 'math', 'law', 'business', 'IS')

To get the effect of inserting new elements into the array, delete zero elements:

$subjects = array('physics', 'chem', 'math');
$new = array('law', 'business');
array_splice($subjects, 2, 0, $new);
// $subjects is array('physics', 'chem', 'law', 'business', 'math')

Although the examples so far have used an indexed array, array_splice( ) also works on associative arrays:

$capitals = array('USA'           => 'Washington',
                  'Great Britain' => 'London',
                  'New Zealand'   => 'Wellington',
                  'Australia'     => 'Canberra',
                  'Italy'         => 'Rome');
$down_under = array_splice($capitals, 2, 2); // remove New Zealand and Australia
$france = array('France' => 'Paris');
array_splice($capitals, 1, 0, $france);      // insert France between USA and G.B.


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.