Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first N elements of an array?

Tags:

arrays

php

What is the best way to accomplish this?

like image 767
GSto Avatar asked Sep 15 '10 17:09

GSto


People also ask

Which function returns an array with the first N elements of the data set?

In Spark, the take function behaves like an array. It receives an integer value (let say, n) as a parameter and returns an array of first n elements of the dataset.

Is the first element of an array 0 or 1?

Zero-based array indexing is a way of numbering the items in an array such that the first item of it has an index of 0, whereas a one-based array indexed array has its first item indexed as 1. Zero-based indexing is a very common way to number items in a sequence in today's modern mathematical notation.


2 Answers

Use array_slice()

This is an example from the PHP manual: array_slice

$input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 0, 3);   // returns "a", "b", and "c" 

There is only a small issue

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag set to trueto avoid this. (4th parameter, available since 5.0.2).

Example:

$output = array_slice($input, 2, 3, true); 

Output:

array([3]=>'c', [4]=>'d', [5]=>'e'); 
like image 71
corbacho Avatar answered Sep 19 '22 15:09

corbacho


You can use array_slice as:

$sliced_array = array_slice($array,0,$N); 
like image 20
codaddict Avatar answered Sep 20 '22 15:09

codaddict