PHP array_slice() Function
Complete PHP Array Reference Manual
Example
Extract from the third element (index 2) of an array and return all elements to the end of the array:
Run Example »
Definition and Usage
The array_slice() function returns a selected portion of an array.
**Note:** If the array has string keys, the returned array will preserve the keys (see Example 4).
Syntax
array_slice(
array,start,length,preserve
)
| Parameters | Description |
|---|---|
| array | Required. Specifies the array. |
| start | Required. Numeric. Specifies where to start extracting elements. 0 = the first element. If this value is positive, extraction starts from the beginning. If it is negative, extraction starts that far from the end of the array. -2 means start from the second-to-last element. |
| length | Optional. Numeric. Specifies the length of the returned array. If this value is an integer, that many elements are returned. If it is negative, extraction stops that far from the end of the array. If not set, all elements from the position set by the start parameter to the end of the array are returned. |
| preserve | Optional. Specifies whether the function preserves or resets keys. Possible values:
|
Technical Details
| Return Value: | Returns the selected portion of the array. |
|---|---|
| PHP Version: | 4+ |
| Changelog: | preserve This parameter was added in PHP 5.0.2. |
More examples
Example 1
Extract from the second element of an array and return two elements:
Run Example »
Example 2
Using a negative start parameter:
Run Example »
Example 3
With the preserve parameter set to true:
Run Example »
Example 4
With string and integer keys:
" red " , " b " => " green " , " c " => " blue " , " d " => " yellow " , " e " => " brown " ) ; print_r ( array_slice ( $a , 1 , 2 ) ) ; $a = array ( " 0 " => " red " , " 1 " => " green " , " 2 " => " blue " , " 3 " => " yellow " , " 4 " => " brown " ) ; print_r ( array_slice ( $a , 1 , 2 ) ) ; ?>Run Example »
Complete PHP Array Reference Manual