Returning first x items from array

2020-01-30 04:22发布

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

标签: php arrays
5条回答
smile是对你的礼貌
2楼-- · 2020-01-30 04:47

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 .

查看更多
来,给爷笑一个
3楼-- · 2020-01-30 04:51

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 );
  }

?>
查看更多
够拽才男人
4楼-- · 2020-01-30 04:57

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.

查看更多
神经病院院长
5楼-- · 2020-01-30 04:58

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

查看更多
beautiful°
6楼-- · 2020-01-30 05:04

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]

查看更多
登录 后发表回答