Backend Development 4 min read

Using PHP's array_slice() Function: Syntax, Parameters, and Examples

This article explains PHP's array_slice() function, detailing its parameters, return value, and usage through multiple code examples that demonstrate extracting subsets of arrays, preserving keys, and omitting length to retrieve remaining elements, plus practical notes for pagination.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_slice() Function: Syntax, Parameters, and Examples

In PHP development, array manipulation is common, and the array_slice() function is a powerful tool for extracting a portion of an array.

The function accepts up to four arguments: the source array, the offset, the length (optional), and a boolean indicating whether to preserve keys. If the length is omitted, the slice continues to the end of the array.

Basic syntax:

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

Examples:

Example 1: Extract the first three elements

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

Result:

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

Example 2: Extract 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);
?>

Result:

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

Example 3: Omit the length to get the remaining part of the array

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

Result:

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

The function does not modify the original array; it returns a new array, making it useful for tasks such as pagination by adjusting the offset and length parameters.

Overall, array_slice() provides a simple and flexible way to handle array subsets in PHP.

backendData ProcessingPHParray-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

login 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.