Alexander Farber
Alexander Farber

Reputation: 23008

PHP how to truncate an array

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

Should I use array_splice?

Upvotes: 26

Views: 38902

Answers (5)

Michael Quad
Michael Quad

Reputation: 330

effectiveness (performance?) depends on which side you wish to truncate (the start or the end) and how many elements you wish to truncate and how big is array.

  1. truncate few elements from the end - unset()
  2. truncate few elements from the start - array_shift()
  3. truncate many elements from any side - re-assigning (re-creating) with array_slice()

these are for index-based arrays of common size, about 100 elements or so, ordered by "effectiveness". array_splice() is used to remove (and re-index) or replace elements (and re-index, when counts dont match) in the array, so it doesn't fit in "truncate" category. i prefer to use this function only for a single element - to remove it.

to equalize (1) and (2) one may posses SplDoublyLinkedList.

Upvotes: 0

uglypointer
uglypointer

Reputation: 359

This function should work

function truncateArray($truncateAt, $arr) {
    array_splice($arr, $truncateAt, (count($arr) - $truncateAt));
    return $arr;
}

Upvotes: 2

Devtronic
Devtronic

Reputation: 39

You can use one of this functions:

function array_truncate(&$arr)
{
    while(count($arr) > 0) array_pop($arr);
}
// OR (faster)
function array_truncate2(&$arr)
{
    array_splice($arr, 0, count($arr));
}

Usage:

$data2 = array("John" => "Doe", "Alice" => "Bob");
array_truncate($data2);
// OR
array_truncate2($data2);

Upvotes: 0

Peter
Peter

Reputation: 16943

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

Upvotes: 24

Marc B
Marc B

Reputation: 360762

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

Upvotes: 4

Related Questions