PHP: Any function that return first/last N elements of an array

后端 未结 2 333
你的背包
你的背包 2021-01-13 20:20

I want a function that will return last/first N element of an array.

For example:

$data = array( \'0\',\'1\',\'2\',\'3\',\'4\',\'5\'         


        
相关标签:
2条回答
  • 2021-01-13 20:35
    function getItems($data, $length, $startLocation){
       if($startLocation == 'first'){
          return array_slice($data, 0, $length);
       }else if($startLocation == 'last'){
          $offset = count($data) - $length - 1;
          if($offset < 0) $offset = 0;
          return array_slice($data, $offset, $length);
       }
    }
    
    0 讨论(0)
  • 2021-01-13 20:44

    You're looking for array_slice() (man page here).

    Example:

    $arr = array(1, 2, 3, 4, 5);
    $slice1 = array_slice($arr, 2); //take all elements from 3rd on
    $slice2 = array_slice($arr, 0, 3); //take first three elements
    
    0 讨论(0)
提交回复
热议问题