PHP 8 reference · Array Functions
PHP array_slice() Function
Return a portion of an array without changing the original, given an offset and an optional length.
PHP 8 Since 4.0
Syntax
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
offset |
Where to start; negative counts from the end. |
length optional |
How many elements; negative stops that many from the end; null takes the rest. |
preserve_keys optional |
true keeps numeric keys instead of renumbering. Default: false |
Return value
The selected elements.
Examples
<?php
$letters = ["a", "b", "c", "d", "e"];
print_r(array_slice($letters, 1, 3));
print_r(array_slice($letters, -2));
Output
Array
(
[0] => b
[1] => c
[2] => d
)
Array
(
[0] => d
[1] => e
)<?php
$posts = range(1, 23);
$page = 3;
$perPage = 10;
echo implode(",", array_slice($posts, ($page - 1) * $perPage, $perPage)), "\n";
Output
21,22,23
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
slice()· Pythonarray.slice()· JavaScript
Related
array_splice()· Remove a portion of an array and optionally replace it with other elements, changing the array in place.array_chunk()· Split an array into smaller arrays of a given size. The last chunk may be smaller.substr()· Return part of a string, given a start position and an optional length. Negative values count from the end.- PHP Arrays · tutorial
- PHP Array Functions · tutorial