PHP how to truncate an array

前端 未结 4 1216
余生分开走
余生分开走 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: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

提交回复
热议问题