array_slice()

array_slice() — Extract a slice of the array.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

Signature

array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

Parameters

ParameterTypeWhat it takes
$arrayarrayThe input array.
$offsetintIf offset is non-negative, the sequence will start at that offset in the array.
$length?intIf length is given and is positive, then the sequence will have up to that many elements in it.
$preserve_keysboolarray_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to true. String keys are always preserved, regardless of this parameter.

Return value

Returns the slice. If the offset is larger than the size of the array, an empty array is returned.

Example

A runnable snippet:

$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 )

See also

array_chunk(), array_splice()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_slice() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.