PHP: how to 'cut' my array?

前端 未结 5 1393
Happy的楠姐
Happy的楠姐 2020-12-10 11:23

I have an array

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

How can I remove

相关标签:
5条回答
  • 2020-12-10 11:53

    http://dev.fyicenter.com/faq/php/php_array_function_6.php

    Look at the one about truncating, particularly array_splice

    0 讨论(0)
  • 2020-12-10 11:55

    Slice it. With a knife.

    Actually, with this:

    array_slice($array, 0, -3);
    

    Assuming you meant cutting off the last 3 elements.

    0 讨论(0)
  • 2020-12-10 11:55

    Use array_splice():

    $new = array_splice($old, 0, 3);
    

    The above line returns the first three elements of $old.

    Important: array_splice() modifies the original array.

    0 讨论(0)
  • 2020-12-10 12:01

    Check out array_slice()

    So, if you wanted the first three elements only:

    $array = array_slice($array, 0, 3);
    

    If you wanted all but the last three elements:

    $array = array_slice($array, 0, -3);
    

    The second parameter is the start point (0 means to start from the begining of the array).

    The third parameter is the length of the resulting array. From the documentation:

    If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

    0 讨论(0)
  • 2020-12-10 12:06

    Use array_splice as:

    $array = array(0,1,2,3,4,5);
    array_splice($array,0,3);
    
    0 讨论(0)
提交回复
热议问题