Get the first N elements of an array?

03/31/2020 21:18:45

What is the best way to accomplish this?

Verified Answer (348 Votes)

09/15/2010 22:25:21

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');
348

Answer #2 (28 Votes)

09/15/2010 22:25:31

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);
28

Answer #3 (12 Votes)

09/15/2010 22:25:12

In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.

12
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.