Mastering PHP's array_slice(): Syntax, Options, and Real-World Examples

This guide explains PHP's array_slice() function, covering its parameters, optional key preservation, and practical examples for extracting subsets, handling pagination, and preserving original arrays without modification.

php Courses
php Courses
php Courses
Mastering PHP's array_slice(): Syntax, Options, and Real-World Examples

PHP provides the powerful array_slice() function for extracting a portion of an array and returning it as a new array. It accepts up to four arguments: the source array, the offset (starting index), the length (number of elements), and an optional boolean to preserve original keys.

The basic syntax is:

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

Parameters: $array – the original array to slice. $offset – index at which to start the slice. $length – how many elements to extract; if omitted, the slice continues to the end. $preserve_keys – when true, retains the original array's keys.

Example 1: Get the first three elements

<?php
$array = [1, 2, 3, 4, 5, 6];
$subset = array_slice($array, 0, 3);
print_r($subset);
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Example 2: Get the last two elements while preserving keys

<?php
$array = [1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e', 6 => 'f'];
$subset = array_slice($array, -2, 2, true);
print_r($subset);
?>

Output:

Array
(
    [5] => e
    [6] => f
)

Example 3: Omit the length to get the remainder of the array

<?php
$array = ['apple', 'banana', 'orange', 'grape', 'watermelon'];
$subset = array_slice($array, 2);
print_r($subset);
?>

Output:

Array
(
    [0] => orange
    [1] => grape
    [2] => watermelon
)

The function does not modify the original array; it returns a new one. To change the source array, assign the result back to it.

In real-world development, array_slice() is frequently used for pagination by adjusting $offset and $length to display different pages of data.

Overall, array_slice() is a simple yet versatile tool for flexible array manipulation in PHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHParray manipulationarray_slice
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.