PHP array_slice() Function
The array_slice() function is a built-in function in PHP that returns a portion of an array according to the offset and length you specify. This function does not modify the original array unless you assign the result back to the original variable.
You can use this function when you want to extract a potion of an array. The general syntax of array_slice() function in PHP is as follows:
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
In the above syntax of array_slice() function,
- $array (required): This parameter represents the name of an array from which a slice will be extracted. An array can be both indexed and associative arrays.
- $offset (required): It represents the starting index of the slice (0-based index). If positive, slicing will start from the begining of the array at that index. If it is negative, slicing will start from the end of the array.
- $length (optional): This parameter represents the number of elements to extract or return. If positive, that number of elements is returned. If negative, it excludes that many elements from the end of the slice. On omitting, all elements from the offset to the end of the array are returned.
- $preserve_keys (optional): If this is set on true, the original keys are preserved. If it is set to false (by default), the numeric keys in the returned array are re-indexed starting from 0.
Thus, PHP array_slice() function returns a new array containing the extracted elements.
Basic Examples of PHP array_slice() Function
Example 1: Simple Slice from Start
<?php
// An indexed array.
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Get elements from index 1 to 3
$slice = array_slice($fruits, 1, 3);
print_r($slice);
?>
Output: Array ( [0] => banana [1] => cherry [2] => date )
In this example, the slice starts at index 1 and goes up to 3 elements.
Example 2: Omitting Length
<?php
// An indexed array.
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Get elements from index 1 to the end.
$slice = array_slice($fruits, 1);
print_r($slice);
?>
Output: Array ( [0] => banana [1] => cherry [2] => date [3] => elderberry )
If you don’t provide a length in the array_slice() function, all remaining elements from the offset are returned.
Example 3: Negative Offset
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
// Slice the last four elements with negative offset.
$slice = array_slice($numbers, -4);
print_r($slice);
?>
Output: Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 )
In this example, negative offset allows you to start slicing from the end of the array. Therefore, the offset -4 starts the slice four elements from the end.
Intermediate Examples
A negative length in array_slice() function allows you to exclude a specified number of elements from the end of the slice. This means the slice will stop before those excluded elements. Let’s take an example on negative length.
Example 4: Negative length
<?php
$colors = ['red', 'green', 'blue', 'yellow', 'cyan', 'magenta'];
// Slice elements from index 1, but exclude the last 3 elements from the end.
$slice = array_slice($colors, 1, -3);
print_r($slice);
?>
Output: Array ( [0] => green [1] => blue )
In this example, the array_slice($colors, 1, -3) takes elements from $offset 1 up to (but not including) the last 3 elements. The slice starts at index 1 (value 2). The negative length -3 means it stops before the last 3 elements (‘yellow’, ‘cyan’, ‘magenta’ are excluded).
Preserving Keys using PHP array_slice() Function
By default, the array_slice() function reindexes the array. If you want to preserve the original keys, you need to set the fourth parameter to true. Preserving keys is especially useful when you work with associative arrays where the keys have semantic meaning. Look at the below example.
Example 5: Associative array
<?php
// An associative array.
$person = [
"name" => "Deepak",
"age" => 34,
"gender" => "Male",
"country" => "USA"
];
$slice = array_slice($person, 1, 2, true);
print_r($slice);
?>
Output: Array ( [age] => 34 [gender] => Male )
Filtering Specific Elements by Position in PHP using array_slice() Function
In some cases, you may need to extract elements from an array based on their position, such as every second or third element. However, PHP doesn’t provide a built-in function directly to achieve it.
You can use a combination of a loop and array_slice() function to extract elements from an array based on their position. Look at the following example code in which we will get every second element from an array.
Example 6:
<?php
$students = ["Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Saanvi"];
$filtered = [];
for($i = 0; $i < count($students); $i += 2) {
$filtered[] = array_slice($students, $i, 1)[0];
}
print_r($filtered);
?>
Output: Array ( [0] => Alice [1] => Charlie [2] => Eva [3] => Saanvi )
In this example, we have created an array of seven student names with indeces 0, 1, 2, 3, 4, . . . . The for loop starts from index 0 and increments by 2 on each iteration. It will run for $i = 0, 2, 4, and 6.
The array_slice($students, $i, 1) function extracts one element from the $student array, starting from index $i. The part [0] accesses that single element and appends it to the empty $filtered array. The following iterations occurs:
- $i = 0 → array_slice($students, 0, 1) → [“Alice”] → add “Alice”
- $i = 2 → array_slice($students, 2, 1) → [“Charlie”] → add “Charlie”
- $i = 4 → array_slice($students, 4, 1) → [“Eva”] → add “Eva”
- $i = 6 → array_slice($students, 6, 1) → [“Saanvi”] → add “Saanvi”
To get every third element, just change the step size in the loop:
for ($i = 0; $i < count($students); $i += 3) { $filtered[] = array_slice($students, $i, 1)[0]; }
PHP array_slice() function is used for extracting subsets from arrays. It works with both indexed and associative arrays. It supports negative offsets and lengths. I hope that you will have understood the basic concepts of array_slice() function and practiced all examples based on them.