Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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): array

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$offsetintThe element to start from, counting from zero. A negative value counts from the end.
$length?intHow many elements to take. Defaults to the rest of the array.
$preserve_keysboolIf `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, 4

The last two elements:

<?php
 
echo implode(', ', array_slice([1, 2, 3, 4, 5], -2));

Output:

4, 5

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.