PHP » Arrays » array_slice()

Syntax:
array array_slice(array array, int start [, int length])
array
Array to be sliced.
start
Where to start the slice.
length
Length of slice or stop element.

Returns part of an array.

The array_slice() function returns part of an array as specified by the start and length parameters. If start is a positive number, it means that the "slice" will start that many elements from the beginning of the array. A negative start will offset the start that many elements from the end of the array instead, the last element being -1. If the length parameter is omitted, the rest of the array is returned. Otherwise, a positive value specifies a maximum length for the returned array. A negative value, on the other hand, specifies a stop element, counted from the back of the array. In this case, the last element counts as 0, although actually passing 0 would count as a length instead.

Examples

Code:
<?php

$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

function element_print($value)
{
   print "$value ";
}

// five elements, starting on the first
array_walk(array_slice($array1, 0, 5), "element_print");
print "<br>";

// the last three elements
array_walk(array_slice($array1, -3), "element_print");
print "<br>";

// elements fourth and fifth counted from the back
array_walk(array_slice($array1, -5, -3), "element_print");

?>
Output:
1 2 3 4 5
7 8 9
5 6
Explanation:

Three different combinations of parameters for array_slice() are shown. Note the inconsistent numbering in the parameters to the third array_slice(). Three elements could easily have been expected.

See Also: