Get the first N elements of an array?
What is the best way to accomplish this?
Verified Answer (348 Votes) ✓
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).
$output = array_slice($input, 2, 3, true);
array(=>'c', =>'d', =>'e');
Answer #2 (28 Votes)
You can use array_slice as:
$sliced_array = array_slice($array,0,$N);
Answer #3 (12 Votes)
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.