PHP array_slice function

Last Updated: February 15, 2022

array_slice — Get a slice from the array

Syntax

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

Supports (PHP 4 , PHP 5, PHP 7, PHP 8)

Parameters

Parameter Description
array target array
offset If postive start from the array and if negative end from the array
length length of the slice
preserve_keys Optional. Specifies if the function should preserve or reset the keys. Possible values:
  • true – Preserve keys
  • false – Default. Reset keys

Return Value

returns the sliced array

Example

$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"
Test