Returning first x items from array

后端 未结 5 624
小蘑菇
小蘑菇 2020-12-01 03:14

I want to return first 5 items from array. How can I do this?

相关标签:
5条回答
  • 2020-12-01 03:39

    A more object oriented way would be to provide a range to the #[] method. For instance:

    Say you want the first 3 items from an array.

    numbers = [1,2,3,4,5,6]

    numbers[0..2] # => [1,2,3]

    Say you want the first x items from an array.

    numbers[0..x-1]

    The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.

    numbers[0..100] # => [1,2,3,4,5,6]

    0 讨论(0)
  • 2020-12-01 03:40

    array_splice — Remove a portion of the array and replace it with something else:

    $input = array(1, 2, 3, 4, 5, 6);
    array_splice($input, 5); // $input is now array(1, 2, 3, 4, 5)
    

    From PHP manual:

    array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement]])
    

    If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length .

    0 讨论(0)
  • 2020-12-01 03:41

    If you just want to output the first 5 elements, you should write something like:

    <?php
    
      if (!empty ( $an_array ) ) {
    
        $min = min ( count ( $an_array ), 5 );
    
        $i = 0;
    
        foreach ($value in $an_array) {
    
          echo $value;
          $i++;
          if ($i == $min) break;
    
        }
    
      }
    
    ?>
    

    If you want to write a function which returns part of the array, you should use array_slice:

    <?php
    
      function GetElements( $an_array, $elements ) {
        return array_slice( $an_array, 0, $elements );
      }
    
    ?>
    
    0 讨论(0)
  • 2020-12-01 03:42

    You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

    0 讨论(0)
  • 2020-12-01 03:44

    array_slice returns a slice of an array

    $sliced_array = array_slice($array, 0, 5)
    

    is the code you want in your case to return the first five elements

    0 讨论(0)
提交回复
热议问题