In PHP, the array_slice function is a common tool used to extract a sub-array from an array. Its function prototype is as follows:
array array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false)
Where, the parameter $length is used to specify the number of elements to be intercepted. However, when $length is 0 or NULL , the behavior is different. This article will analyze in detail the difference between array_slice in these two cases.
$array : The input array.
$offset : where to start intercepting, negative numbers are supported.
$length : The number of intercepted elements, the default NULL means that it is intercepted to the end of the array.
$preserve_keys : Whether to keep the key name of the original array.
When you call array_slice , if no $length parameter is passed in or the value passed in is NULL , PHP will intercept from $offset to the end of the array.
Example:
$arr = [1, 2, 3, 4, 5];
$result = array_slice($arr, 2, NULL);
print_r($result);
Output:
Array
(
[0] => 3
[1] => 4
[2] => 5
)
Explanation: Starting from Index 2, intercepting to the end of the array.
When $length is explicitly set to 0 , array_slice returns an empty array. That is, no matter how long the array is, the intercepted length is zero, meaning that no elements are returned.
Example:
$arr = [1, 2, 3, 4, 5];
$result = array_slice($arr, 2, 0);
print_r($result);
Output:
Array
(
)
Explanation: Specify the length to 0 and do not intercept any elements.
length parameter | Return result | illustrate |
---|---|---|
NULL | All elements from offset to the end of the array | Default behavior, intercept all remaining elements |
0 | Empty array | Intercept the length of 0, and the result is an empty array |
If you want to intercept the tail of the array, it is recommended to omit the $length parameter or explicitly pass NULL .
If you want to avoid accidentally returning empty arrays, be careful not to set $length to 0 .
For dynamically passed parameters, make type judgments to avoid passing 0s to affect the results.
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$result = array_slice($arr, 1, NULL, true);
print_r($result);
Output:
Array
(
[b] => 2
[c] => 3
)
Here, NULL is passed in to intercept all remaining elements, while maintaining the original key name.
PHP official documentation: https://gitbox.net/manual/en/function.array-slice.php