array_slice in PHP

Syntax of array_slice

array array_slice(array array, int offset[, int length][, bool keepkeys])

Returns an array containing a set of elements pulled from the given array. If offset is a positive number, elements starting from that index onward are used; if offset is a negative number, elements starting that many elements from the end of the array are used.

If the third argument is provided and is a positive number, that many elements are returned; if negative, the sequence stops that many elements from the end of the array. If the third argument is omitted, the sequence returned contains all elements from the offset to the end of the array.

If keep keys, the fourth argument, is true, then the order of numeric keys will be preserved; otherwise they will be renumbered and resorted

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

Output

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Leave a Comment