[php] Get the first N elements of an array?

What is the best way to accomplish this?

This question is related to php arrays

The answer is


array_slice() is best thing to try, following are the examples:

<?php
$input = array("a", "b", "c", "d", "e");

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

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

if you want to get the first N elements and also remove it from the array, you can use array_splice() (note the 'p' in "splice"):

http://docs.php.net/manual/da/function.array-splice.php

use it like so: $array_without_n_elements = array_splice($old_array, 0, N)


You can use array_slice as:

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

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.