The array_slice() function returns selected parts of an array.
PHP array_slice() Function has the following syntax.
array_slice(array,start,length,preserve)
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to slice |
start | Required. | Starting point. 0 = the first element. negative value mean to slice from last element. -2 means start at the second last element of the array. |
length | Optional. | length of the returned array. negative number means stop slicing that far from the last element. If not set, the function will return all elements, starting from start. |
preserve | Optional. | preserve or reset the keys. |
Possible values for preserve:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,2));
?>
The code above generates the following result.
Start the slice from from the second array element, and return only two elements:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,1,2));
?>
The code above generates the following result.
Using a negative start parameter:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,-2,1));
?>
The code above generates the following result.
With the preserve parameter set to true:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,1,2,true));
?>
The code above generates the following result.
With both string and integer keys:
<?php
$a=array("a"=>"Java","b"=>"PHP","c"=>"java2s.com","d"=>"HTML","e"=>"java2s.com");
print_r(array_slice($a,1,2));
$a=array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"java2s.com");
print_r(array_slice($a,1,2));
?>
The code above generates the following result.