PHP how to truncate an array

前端 未结 4 1208
余生分开走
余生分开走 2020-12-17 09:02

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

Should I use array_splice?

相关标签:
4条回答
  • 2020-12-17 09:41

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

    0 讨论(0)
  • 2020-12-17 09:48

    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

    0 讨论(0)
  • 2020-12-17 09:53

    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);
    
    0 讨论(0)
  • 2020-12-17 09:55

    This function should work

    function truncateArray($truncateAt, $arr) {
        array_splice($arr, $truncateAt, (count($arr) - $truncateAt));
        return $arr;
    }
    
    0 讨论(0)
提交回复
热议问题