Reputation: 23008
How do you truncate a PHP array in a most effective way?
Should I use array_splice?
Upvotes: 26
Views: 38902
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.
unset()
array_shift()
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
Reputation: 359
This function should work
function truncateArray($truncateAt, $arr) {
array_splice($arr, $truncateAt, (count($arr) - $truncateAt));
return $arr;
}
Upvotes: 2
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
Reputation: 16943
You can use the native functions to remove array elements:
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