PHP array_slice() Function
Example
Starts from the third element of the array and returns the rest of the elements in the array:
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?>
Definition and Usage
The array_slice() function retrieves a segment of values from the array based on conditions and returns them.
Note:If the array has string keys, the returned array will retain the key names. (See example 4)
Syntax
array_slice(array,start,length,preserve)
Parameter | Description |
---|---|
array | Required. Specifies the array. |
start |
Required. Numeric. Specifies the starting position of the elements to be retrieved. 0 = the first element. If this value is set to a positive number, it will start from the front. If this value is set to a negative number, it will start from the end towards the front based on the absolute value of start. -2 means starting from the second-to-last element of the array. |
length |
Optional. Numeric. Specifies the length of the returned array. If this value is set to an integer, it returns this number of elements. If this value is set to a negative number, the function will stop taking at this distance from the end of the example array. If this value is not set, it returns all elements from the position set by the start parameter to the end of the array. |
preserve |
Optional. Specifies whether the function should keep the key names or reset them. Possible values:
|
Technical Details
Return Value: | Returns the selected part of the array. |
PHP Version: | 4+ |
Update Log: | Added in PHP 5.0.2 preserve Parameters. |
More Examples
Example 1
Start from the second element of the array and return only two elements:
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,2)); ?>
Example 2
Using Negative start Parameters:
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,-2,1)); ?>
Example 3
Take preserve Parameter Set to True:
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,2,true)); ?>
Example 4
Handling String Keys and Integer Keys:
<?php $a=array("a"=>"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)); ?>