4.6. Changing Array Size
Problem
You want to modify the size of an array, either by making it larger or smaller than its current size.
Solution
Use array_pad( )
to make an array grow:
// start at three
$array = array('apple', 'banana', 'coconut');
// grow to five
$array = array_pad($array, 5, '');Now, count($array) is 5, and
the last two elements contain the empty string.
To reduce an array, you can use array_splice( ):
// no assignment to $array array_splice($array, 2);
This removes all but the first two elements from
$array.
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 ...
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