The array_slice function returns a specific part of the array. If the array consists of numeric keys, then the selected part will contain the keys starting from 0. But, if the keys are string, then they are preserved even in the selected part.
What is the syntax of the array_slice function in PHP?
array_slice(array, start, length, preserve)
Parameter | Description |
---|---|
array | The array to get a slice from – Required |
start | Define the starting element/position for slicing. When set to negative: Start slicing from the right side (end) of the array. For example, -2 means start slicing from the second last element of the array – Required |
length | Defines the length of the sliced part of the array starting from the start element. When set to a negative number: it starts slicing from the right to the left side of the array (from the last towards the beginning) When left empty: Return all the elements from the start element to the end of the array – Optional |
preserve | Boolean Parameter When set to true: The keys will be preserved in the sliced output. When set to false: The keys will not be preserved in the sliced output. – Optional |
Examples of array_slice function
Example 1. Start slicing the array from the second element and return the rest of the array elements.
<?php
$arr=array("R","G","B","Y","Br");
print_r(array_slice($arr,1));
?>
Example 2. Start slicing the array from the second element and return two elements.
<?php
$arr=array("R","G","B","Y","Br");
print_r(array_slice($arr,1,2));
?>
Example 3. Start slicing the array from the second last element and return two elements.
<?php
$arr=array("R","G","B","Y","Br");
print_r(array_slice($arr,-1,2));
?>
Example 4. Start slicing the array from the second element and return two elements with preserved keys.
<?php
$arr=array("R","G","B","Y","Br");
print_r(array_slice($arr,1,2,true));
?>
Example 5. Array slice example with both numeric and string keys.
<?php
$arr=array("a"=>"1","b"=>"2","c"=>"3","d"=>"4","e"=>"5");
print_r(array_slice($arr,2,2));
$arr=array("0"=>"R","1"=>"G","2"=>"B","3"=>"Y","4"=>"Br");
print_r(array_slice($arr,2,2));
?>