Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to truncate an array

Tags:

How do you truncate a PHP array in a most effective way?

Should I use array_splice?

like image 227
Alexander Farber Avatar asked Nov 02 '11 18:11

Alexander Farber


2 Answers

You can use the native functions to remove array elements:

  • array_pop - Pop the element off the end of array
  • array_shift - Shift an element off the beginning of array
  • array_slice - Extract a slice of the array
  • unset - Remove one element from array

With this knowledge make your own function

function array_truncate(array $array, $left, $right) {     $array = array_slice($array, $left, count($array) - $left);     $array = array_slice($array, 0, count($array) - $right);     return $array; } 

Demo - http://codepad.viper-7.com/JVAs0a

like image 150
Peter Avatar answered Oct 12 '22 20:10

Peter


Yes, unless you want to loop over the array and unset() the unwanted elements.

like image 31
Marc B Avatar answered Oct 12 '22 21:10

Marc B