- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.4 Enlarging or Shrinking an Array
You want to make an array bigger or cut off items at the end of an array. You think that enlarging an array can be useful because it is more memory efficient to set aside space.
Technique
In PHP, it is unnecessary to preallocate your arrays to a certain length. You simply store the data in the array at the indices/keys that you want, and let PHP handle the grunge work of memory allocation internally:
<?php $list = array(); // $list will not be 51 elements long, it has only 1 entry // an index 50 $list[50] = "orange"; ?>
To shrink an array, use the array_splice() function (PHP 4 only):
<?php $list = array ("dog", "cat", "rabbit", "ant", "horse", "cow"); // trim the list to five elements array_splice ($list, 5); ?>
Comments
The array_splice() function takes up to four arguments:
array array_splice(array init, int start, int length, array replacement);
The first argument of array_splice() is the initial array that you want to manipulate, followed by where you want to start your replacement or subtraction in the array; if left empty, the replacement or subtraction will start with the first element. length is how many array elements you want to replace; if left empty, array_splice() will replace all elements from the start. Finally, array_splice() takes a replacement array for the part of the array that is deleted. The array_splice() function returns the elements of the array that are taken out and the original array is modified (destructively). Please note that array_splice() was just added in PHP 4. The following is some PHP3 code that will remove all but the first five elements:
<?php reset ($ar); $i = 0; while ($i < 5 && list ($key, $val) = each ($ar)) { $new_ar[$key] = $ar[$val]; $i++; } $ar = $new_ar; ?>
To enlarge an array to a certain number of elements, you have to give a value to each array element:
<?php for ($c = 0; $c < 100; $c++) { $ar[$c] = ""; } ?>
This can also be done with the array_pad() function:
<?php $some_ar = array(); $some_ar = array_pad ($some_ar, 100, ""); ?>