Trunc or Resize Array Size in PHP – Easy Coding

If you want to modify the size of an array, larger or smaller than its current size, use array_pad() and array_splice() function.

How to make an array grow:

  1. /***** start with 2 elements *****/
  2. $array = array('element1', 'element2');
  3. /***** grow to 4 elements *****/
  4. $array = array_pad($array, 4,'');
/***** start with 2 elements *****/
$array = array('element1', 'element2');

/***** grow to 4 elements *****/
$array = array_pad($array, 4,'');

How to reduce an array:

  1. /***** shrink to three elements ***** /
  2. array_splice($array, 3);
/***** shrink to three elements ***** /
array_splice($array, 3);

or

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

 

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *