PHP Reference ยท Array Functions
PHP array_slice() function
Reference for PHP array_slice(): copy part of an array by offset and length, use negative positions, and control whether keys are preserved.
array_slice() returns a part of an array without changing the original. You say where the slice starts (the offset) and how many elements to take (the length), and you get a new array back.
By default the numeric keys of the result are renumbered from 0, while string keys are always kept. Pass true as the last argument to keep the original numeric keys too.
<?php $letters = ["a", "b", "c", "d", "e"]; print_r(array_slice($letters, 1, 3)); // b, c, d
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_slice( array $array, int $offset, ?int $length = null, bool $preserve_keys = false ): array
| Name | Description |
|---|---|
$array |
The input array. It is not modified. |
$offset |
Where the slice starts. A negative value counts from the end of the array. |
$length |
How many elements to take. A negative value stops that many elements before the end. null (the default) means "to the end". |
$preserve_keys |
If true, integer keys are kept. String keys are always kept. Defaults to false. |
Return value: a new array with the selected elements. It is empty if the offset is beyond the end of the array.
Usage notes
- Positions are by order, not by key. The offset counts elements from the start of the array, so
array_slice(["a" => 1, "b" => 2], 1)returns["b" => 2]. - Integer keys are renumbered unless
$preserve_keysistrue. Forgetting this is a common bug when you later look up elements by their old index. - Sorted results: if you need "the first N" of a sorted list, sort first, then slice.
- Not for removing.
array_slice()copies; to cut elements out of the original array usearray_splice(). - Strings have their own function: use
substr()for text andmb_substr()for multibyte text. - Large arrays: the function walks the array up to the offset, so repeated slicing of a very big array in a loop can be slow. Consider
array_chunk()to split once. nulllength: passingnullexplicitly is the same as leaving the argument out.
Related
array_splice(),array_chunk(),array_values(),substr()- Lessons: Arrays, Array functions