Home >Backend Development >PHP Tutorial >php function array_slice() that returns a selected part of an array
Example
Start taking out the second element of the array and return all elements until the end of the array:
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?>
Definition and usage
array_slice() function return Selected portion of the array.
Note: If the array has string keys, the returned array will retain the keys (see Example 4).
Syntax
array_slice(array,start,length,preserve)
Parameters | Description |
array | Required. Specifies an array. |
start | Required. numerical value. Specifies the starting position of the element to be retrieved. 0 = first element. If the value is set to a positive number, it will be taken from front to back. If the value is set to a negative number, the absolute value of start is taken from back to front. -2 means start from the second to last element of the array. |
length | Optional. numerical value. Specifies the length of the returned array. If the value is set to an integer, that number of elements is returned. If this value is set to a negative number, the function will terminate fetching this far from the end of the example array. If this value is not set, all elements starting from the position set by the start parameter to the end of the array are returned. |
preserve | Optional. Specifies whether the function retains key names or resets key names. Possible values:
|
Technical details
Return value: | Return the selected portion of the array. |
PHP Version: | 4+ |
##Update Log : | The preserve parameter is new in PHP 5.0.2.
The above is the detailed content of php function array_slice() that returns a selected part of an array. For more information, please follow other related articles on the PHP Chinese website!