Using PHP array_slice() to Extract Subarrays – Syntax, Parameters, and Practical Examples
This article explains the PHP array_slice() function, detailing its parameters, basic syntax, and providing three clear code examples that demonstrate extracting portions of arrays, preserving keys, and omitting length for pagination-like operations.
In PHP development, the array_slice() function is a powerful tool for extracting a portion of an array and returning it as a new array.
The function accepts up to four arguments: the source array, the starting offset, the length of elements to extract (optional), and a boolean indicating whether to preserve the original keys.
Basic syntax:
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 extraction.
$length : number of elements to extract; if omitted, extraction continues to the end of the array.
$preserve_keys : whether to keep the original keys (default false ).
Example 1 – extracting 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 – extracting 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 – omitting the length parameter to get the remaining part 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
)These examples show that array_slice() is simple yet versatile, allowing developers to extract sub‑arrays, optionally keep original keys, and use it for tasks such as pagination by adjusting $offset and $length .
Note that array_slice() does not modify the original array; it returns a new array, so any changes must be assigned back to the source if needed.
Overall, array_slice() provides a flexible way to handle array data in PHP backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.