array_slice
Returns part of an array.
Available since: PHP 4
Syntax
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| $offset | int | The element to start from, counting from zero. A negative value counts from the end. |
| $length | ?int | How many elements to take. Defaults to the rest of the array. |
| $preserve_keys | bool | If `true`, numeric keys are not renumbered. |
Return value
arrayA new array with the selected elements.
Examples
Three elements starting from the second:
<?php
echo implode(', ', array_slice([1, 2, 3, 4, 5], 1, 3));Output:
2, 3, 4The last two elements:
<?php
echo implode(', ', array_slice([1, 2, 3, 4, 5], -2));Output:
4, 5Notes
The function is handy for pagination: array_slice($items, ($page - 1) * $perPage, $perPage).
See also
- array_reverse — Returns an array with its elements in reverse order.
- array_pop — Removes the last element of an array and returns it.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.