W3docs

PHP array_slice function: A comprehensive guide

Learn how to use PHP array_slice() to extract part of an array by offset and length, with negative indexes, key preservation, and practical examples.

array_slice() extracts a portion of a PHP array and returns it as a new array, leaving the original untouched. It is the right tool whenever you need "give me elements 5 through 10," the first or last N items, or a page of results. This guide covers the function signature, how the $offset, $length, and $preserve_keys arguments behave (including negative values), the gotcha around numeric keys, and several practical patterns.

What is the PHP array_slice function?

The array_slice function is a built-in PHP function that allows you to extract a slice of an array, based on a starting index and a length. The syntax of the function is as follows:

PHP array_slice function syntax

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
  • $array — the array to slice. It is passed by value, so the original array is never modified.
  • $offset — the starting index of the slice. If positive, the slice starts that many elements from the front. If negative, it starts that many elements from the end of the array (-2 means "start at the second-to-last element").
  • $length (optional) — how many elements to take. If omitted or null, the slice runs to the end of the array. If negative, the slice stops that many elements before the end. If larger than the remaining elements, you simply get whatever is left.
  • $preserve_keys (optional, default false) — see the key-preservation note below.

The function returns a new array containing the selected elements; the original is left intact.

Negative offset and length

Negative values count from the end, which makes "the last N items" and "everything except the last item" trivial:

PHP array_slice with negative offset and length

<?php
$letters = array("a", "b", "c", "d", "e");

print_r(array_slice($letters, -2));    // last 2: Array ( [0] => d [1] => e )
print_r(array_slice($letters, 1, -1)); // skip first and last: Array ( [0] => b [1] => c [2] => d )
?>

How keys are handled

By default array_slice() reindexes numeric keys starting from 0, but it always preserves string (associative) keys. Set the fourth argument to true when you need the original numeric keys to survive:

PHP array_slice key preservation

<?php
$num = array(10 => "x", 20 => "y", 30 => "z");

print_r(array_slice($num, 1));             // reindexed: Array ( [0] => y [1] => z )
print_r(array_slice($num, 1, null, true)); // kept:      Array ( [20] => y [30] => z )
?>

The earlier syntax example shows $preserve_keys = true combined with a negative offset:

PHP array_slice with preserved keys and negative offset

<?php
$assoc = array("a" => 1, "b" => 2, "c" => 3, "d" => 4);
$slice = array_slice($assoc, -2, 2, true);
print_r($slice); // Output: Array ( [c] => 3 [d] => 4 )
?>

How to use the PHP array_slice function?

Using the array_slice function is very straightforward. Here's an example that demonstrates how to extract a slice of an array, starting from the third element, and including the next two elements:

How to use the PHP array_slice function

php— editable, runs on the server

As you can see, the resulting slice contains the elements "cherry" and "date", which are the two elements starting from the third element of the original array.

Practical examples of using the PHP array_slice function

Now that you know how to use the array_slice function, let's look at some practical examples of its usage.

Paginating results

If you're working with a large dataset, such as a list of products or blog posts, you may want to display the results in a paginated manner, to avoid overwhelming the user with too much information at once. The array_slice function can be very useful in this context, as it allows you to extract a slice of the dataset based on the current page number and the number of items per page. Here's an example that demonstrates how to do this:

PHP Paginating results with function array_slice

<?php

$dataset = range(1, 100); // Simulated dataset
$page = $_GET["page"] ?? 1; // Default to page 1 if not set
$itemsPerPage = 10;
$startIndex = ($page - 1) * $itemsPerPage;
$slice = array_slice($dataset, $startIndex, $itemsPerPage);

?>

Removing elements from an array

If you have an array that contains elements you want to remove, you can combine array_slice() with array_merge() to build a new array that excludes them. (If you would rather remove elements in place and modify the original array, use array_splice() instead.) Here's an example:

PHP use the array_slice function in combination with the array_merge function

php— editable, runs on the server

Reordering elements in an array

If you have an array that contains elements you want to reorder, you can use the array_slice function in combination with the array_merge function to create a new array that includes the elements in the desired order. Here's an example that demonstrates how to do this:

PHP Reordering elements in an array

php— editable, runs on the server

As you can see, the resulting array contains the same elements as the original array, but in a different order.

Conclusion

array_slice() extracts part of an array without touching the original, making it ideal for pagination, taking the first or last N items, and building reordered copies. Remember the two key behaviors: negative $offset/$length count from the end, and numeric keys are reindexed unless you pass $preserve_keys = true.

To go further, see array_splice() for in-place removal/replacement, array_merge() for joining slices back together, and the PHP arrays overview for a refresher on how arrays and keys work.

Practice

Practice
What does the array_slice() function in PHP do?
What does the array_slice() function in PHP do?
Was this page helpful?