Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning first x items from array

Tags:

arrays

php

People also ask

How do you return the first value in an array?

Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array.

How do you find the first three items of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.

How do you return the first and last element of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.


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


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 .


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

?>