GSto
GSto

Reputation: 42350

Get the first N elements of an array?

What is the best way to accomplish this?

Upvotes: 268

Views: 222266

Answers (5)

Alon G
Alon G

Reputation: 3373

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)

Upvotes: 8

Abdur Rehman
Abdur Rehman

Reputation: 3293

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));
?>

Upvotes: 8

corbacho
corbacho

Reputation: 9042

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

Upvotes: 463

codaddict
codaddict

Reputation: 455122

You can use array_slice as:

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

Upvotes: 35

Fanis Hatzidakis
Fanis Hatzidakis

Reputation: 5340

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.

Upvotes: 12

Related Questions