How to Slice an Array in PHP?
Last Updated :
23 Jul, 2025
In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to help you do this task quickly.
These are the following approaches:
Using array_slice() Function
The array_slice() function is the standard way to slice an array in PHP. This function allows you to specify the starting index, the length of the slice, and whether to preserve the array keys.
Syntax:
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
Example: This example shows the creation of a custom function to slice an array.
PHP
<?php
$input = [1, 2, 3, 4, 5, 6, 7];
$slice = array_slice($input, 2, 3);
print_r($slice);
?>
OutputArray
(
[0] => 3
[1] => 4
[2] => 5
)
Using a Custom Function
Even though array_slice() usually works well, you can write a custom function to slice an array by hand. This could be helpful when adding more logic to the slicing process or in learning scenarios.
Syntax:
function custom_slice(array $array, int $offset, int $length): array {
$sliced_array = [];
for ($i = $offset; $i < $offset + $length; $i++) {
if (isset($array[$i])) {
$sliced_array[] = $array[$i];
}
}
return $sliced_array;
}Example: This example shows the creation of a custom function to slice an array.
PHP
<?php
// Define the custom_slice() function
function custom_slice(array $array, int $offset, int $length): array {
$sliced_array = [];
for ($i = $offset; $i < $offset + $length; $i++) {
if (isset($array[$i])) {
$sliced_array[] = $array[$i];
}
}
return $sliced_array;
}
// Now call the custom_slice() function
$input = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
$slice = custom_slice($input, 1, 3);
print_r($slice);
?>
OutputArray
(
[0] => banana
[1] => cherry
[2] => date
)
Explore
Basics
Array
OOPs & Interfaces
MySQL Database
PHP Advance