Get the first N elements of an array?

后端 未结 5 1505
一整个雨季
一整个雨季 2020-11-27 02:19

What is the best way to accomplish this?

相关标签:
5条回答
  • 2020-11-27 02:59

    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));
    ?>
    
    0 讨论(0)
  • 2020-11-27 03:02

    You can use array_slice as:

    $sliced_array = array_slice($array,0,$N);
    
    0 讨论(0)
  • 2020-11-27 03:08

    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');
    
    0 讨论(0)
  • 2020-11-27 03:18

    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)

    0 讨论(0)
  • 2020-11-27 03:24

    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.

    0 讨论(0)
提交回复
热议问题