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, ""); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net