PHP how to truncate an array

70

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

Should I use array_splice?

742

Answer

Solution:

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

342

Answer

Solution:

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

183

Answer

Solution:

This function should work

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

Answer

Solution:

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);

People are also looking for solutions to the problem: php - Group multidimensional array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.