Get the first N elements of an array?

PhpArrays

Php Problem Overview


What is the best way to accomplish this?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

You can use array_slice as:

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

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGStoView Question on Stackoverflow
Solution 1 - PhpcorbachoView Answer on Stackoverflow
Solution 2 - PhpcodaddictView Answer on Stackoverflow
Solution 3 - PhpFanis HatzidakisView Answer on Stackoverflow
Solution 4 - PhpAbdur RehmanView Answer on Stackoverflow
Solution 5 - PhpAlon GouldmanView Answer on Stackoverflow