Using PHP's array_slice() Function: Syntax, Parameters, and Practical Examples
This article explains PHP's array_slice() function, detailing its parameters, syntax, and providing multiple code examples that demonstrate extracting subsets of arrays, preserving keys, and using the function for pagination and other common backend tasks.
In PHP development, array manipulation is common, and the array_slice() function is a powerful tool for extracting a portion of an array.
The array_slice() function returns a new array containing a slice of the original array. It accepts three main arguments: the source array, the starting offset, and the length of the slice; an optional fourth argument determines whether to preserve the original keys.
Basic syntax of array_slice() is:
array array_slice(array $array, int $offset, int $length = null, bool $preserve_keys = false)Where $array is the input array, $offset is the index at which to start, $length is the number of elements to extract, and $preserve_keys indicates whether to keep the original keys.
Below are several simple examples illustrating the usage of array_slice() :
Example 1: Extract the first three elements of an array
<?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: 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);
?>Output:
Array
(
[5] => e
[6] => f
)Example 3: Omit 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. It can extract any part of an array and optionally retain the original keys, making it useful for tasks such as pagination where the $offset and $length parameters control which page of data is displayed.
Note that array_slice() does not modify the original array; it returns a new array. If you need to modify the original array, assign the result back to it.
In summary, the array_slice() function is a highly practical PHP array handling function that provides flexible data extraction capabilities.
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.