Take the 2-minute tour ×

What is the best way to accomplish this?

share|improve this question
if you ever need to find a function to do something with an array go here: php.net/manual/en/function.array.php and look through the functions. –  Galen Sep 15 '10 at 17:27
rather than coming over to SO !? –  Hrishikesh Choudhari Jul 27 '11 at 6:57
add comment

3 Answers

up vote 63 down vote accepted

Use array_slice()

This is an example from the PHP manual: array_slice

$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)

share|improve this answer
Wow, 3 year edit :) Nice job. –  webnoob Jan 27 at 22:05
add comment

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


