home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

4.7. Changing Array Size

4.7.3. Discussion

Arrays aren't a predeclared size in PHP, so you can resize them on the fly.

To pad an array, use array_pad( ). The first argument is the array to be padded. The next argument is the size and direction you want to pad. To pad to the right, use a positive integer; to pad to the left, use a negative one. The third argument is the value to be assigned to the newly created entries. The function returns a modified array and doesn't alter the original.

Here are some examples:

// make a four-element array with 'dates' to the right
$array = array('apple', 'banana', 'coconut');
$array = array_pad($array, 4, 'dates');
print_r($array);
Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => dates
)

// make a six-element array with 'zucchinis' to the left
$array = array_pad($array, -6, 'zucchini');
print_r($array);
Array
(
    [0] => zucchini
    [1] => zucchini
    [2] => apple
    [3] => banana
    [4] => coconut
    [5] => dates
)

Be careful. array_pad($array, 4, 'dates') makes sure an $array is at least four elements long, it doesn't add four new elements. In this case, if $array was already four elements or larger, array_pad( ) would return an unaltered $array.

Also, if you declare a value for a fourth element, $array[4]:

$array = array('apple', 'banana', 'coconut');
$array[4] = 'dates';

you end up with a four-element array with indexes 0, 1, 2, and 4:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [4] => dates
)

PHP essentially turns this into an associative array that happens to have integer keys.

The array_splice( ) function, unlike array_pad( ), has the side-effect of modifying the original array. It returns the spliced out array. That's why you don't assign the return value to $array. However, like array_pad( ), you can splice from either the right or left. So, calling array_splice( ) with a value of -2 chops off the last two elements from the end:

// make a four-element array
$array = array('apple', 'banana', 'coconut', 'dates');

// shrink to three elements
array_splice($array, 3);

// remove last element, equivalent to array_pop( )
array_splice($array, -1);

// only remaining fruits are apple and banana
print_r($array);
Array
(
    [0] => apple
    [1] => banana
)


Library Navigation Links

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