How do you truncate a PHP array in a most effective way?
Should I use array_splice?
Yes, unless you want to loop over the array and unset() the unwanted elements.
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
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);
This function should work
function truncateArray($truncateAt, $arr) {
array_splice($arr, $truncateAt, (count($arr) - $truncateAt));
return $arr;
}