array_slice

Extracts a portion of an array by offset and length without modifying the original.

Signature
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$arrayarrayThe input array. It is not modified.
$offsetintWhere the slice starts. A negative offset counts back from the end of the array.
$lengthoptional?int= nullHow many elements to take. Null takes everything to the end; a negative value stops that many elements before the end.
$preserve_keysoptionalbool= falseWhen true, integer keys are kept. String keys are always preserved.

Return value

arrayA new array containing the extracted elements. Returns an empty array if the offset is beyond the end.

Errors

Throws a TypeError if $array is not an array or $offset is not an int.

array_slice() copies a run of elements out of an array. It is the read-only counterpart of array_splice(): the source array is never touched.

When to reach for it

Pagination is the classic use — array_slice($rows, ($page - 1) * $perPage, $perPage). It is also how you take the top N of a sorted array, drop a leading header, or grab the last few entries of a log with a negative offset. When the offset is past the end you get an empty array rather than an error, which makes it safe to call with computed page numbers.

What trips people up

Integer keys are renumbered from 0 by default. Slicing rows keyed by id and then using those keys will quietly give you 0, 1, 2. Pass true as the fourth argument to keep them. String keys are always preserved, so an associative array survives the default behaviour unchanged.

A negative length is not a count — it is a stop position measured from the end. array_slice($a, 1, -1) means "from the second element up to but not including the last", which is a neat way to strip the first and last item at once.

Slicing does not deep-copy: nested arrays and objects in the result still reference the same data.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Paginate an in-memory result set into fixed-size pages.
  • Take the top 10 of an array you just sorted by score.
  • Trim the first and last elements of a list in one call with a negative length.

Frequently asked questions

What is the difference between array_slice and array_splice?

array_slice returns a copy and leaves the original array alone; array_splice removes the elements from the original array in place and can insert replacements. Use slice for reading, splice for editing.

Does array_slice preserve keys?

String keys are always preserved. Integer keys are renumbered from 0 unless you pass true as the fourth argument.

How do I get the last N elements of an array?

Use a negative offset: array_slice($array, -3) returns the last three elements. Negative offsets count back from the end of the array.

More examples

Top N after sorting

arsort sorts by value descending and keeps keys. The slice then takes the first two entries: bob => 91 and dee => 88. String keys are preserved even without the fourth argument, but passing true makes the intent explicit.

Example · php
<?php
$scores = ['ann' => 42, 'bob' => 91, 'cal' => 67, 'dee' => 88];
arsort($scores);
print_r(array_slice($scores, 0, 2, true));

Offsets past the end are safe

An offset beyond the end yields an empty array rather than a warning. A negative offset larger than the array is clamped to the start, and an oversized length simply stops at the end.

Example · php
<?php
$items = ['a', 'b', 'c'];
var_dump(array_slice($items, 10, 5));
var_dump(array_slice($items, -99, 2));
var_dump(array_slice($items, 2, 100));

Slice does not modify the source

$middle holds 2, 3, 4 while $original is unchanged with all five elements. If you wanted the elements removed from the source as well, that is array_splice.

Example · php
<?php
$original = [1, 2, 3, 4, 5];
$middle = array_slice($original, 1, 3);
print_r($middle);
print_r($original);
echo count($original), " elements still there\n";

Discussion

  • Be the first to comment on this lesson.