PHP get the last 3 elements of an array

后端 未结 4 1617
醉梦人生
醉梦人生 2020-12-01 06:11

I have an array:

[13] => Array
        (
            [0] => joe
            [1] => 0

    [14] => Array
        (
            [0] => bob
             


        
相关标签:
4条回答
  • 2020-12-01 06:26

    You can use array_slice():

    <?php
        // -3 = start from the end
        // true = preserve_keys
        $result = array_slice($array, 0, -3, true); 
    ?>
    
    0 讨论(0)
  • 2020-12-01 06:43

    Use array_slice:

    $res = array_slice($array, -3, 3, true);
    
    0 讨论(0)
  • 2020-12-01 06:45

    If you want to preserve key, you can pass in true as the fourth argument:

    array_slice($a, -3, 3, true);
    
    0 讨论(0)
  • 2020-12-01 06:47

    You can use array_slice with offset as -3 so you don't have to worry about the array length also by setting preserve_keys parameter to TRUE.

    $arr = array_slice($arr,-3,3,true);                                             
    
    0 讨论(0)
提交回复
热议问题