Returning first x items from array

PhpArrays

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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 .

Solution 3 - Php

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

?>

Solution 4 - Php

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.

Solution 5 - Php

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionO..View Question on Stackoverflow
Solution 1 - PhpknittlView Answer on Stackoverflow
Solution 2 - PhpAndrejs CainikovsView Answer on Stackoverflow
Solution 3 - PhpAnaxView Answer on Stackoverflow
Solution 4 - PhpCesarView Answer on Stackoverflow
Solution 5 - PhpJasonView Answer on Stackoverflow