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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
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

Take part of an arrayTry it yourself
<?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
)
PaginateTry it yourself
<?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

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?