Get the first N elements of an array?
What is the best way to accomplish th开发者_如何学Pythonis?
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 true
to 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');
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.
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)
精彩评论