Start with the second element of the array and return all elements up to the end of the array:
<?php$a=array("red","green","blue","yellow","brown");print_r(array_slice($a,2));?>The array_slice() function returns the selected portion of an array.
Note: If the array has string keys, the returned array will retain the keys (see Example 4).
array_slice( array,start,length,preserve )
parameter | describe |
---|---|
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: true - keep key names false - default. Reset key name |
Return value: | Returns the selected portion of an array. |
---|---|
PHP version: | 4+ |
Update log: | The preserve parameter is new in PHP 5.0.2. |
Start taking out the first element of the array and return two elements:
<?php$a=array("red","green","blue","yellow","brown");print_r(array_slice($a,1,2));?>Use a negative start parameter:
<?php$a=array("red","green","blue","yellow","brown");print_r(array_slice($a,-2,1));?>With the preserve parameter set to true:
<?php$a=array("red","green","blue","yellow","brown");print_r(array_slice($a,1,2,true));?>With string and integer key names:
<?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));?>