From http://www.w3schools.com (Copyright Refsnes Data)
The array_slice() function returns selected parts of an array.
array_slice(array,start,length,preserve) |
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start the slice.
0 = the first element.
If this value is set to a negative number, the function will start slicing that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies the length of the returned array.
If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
|
preserve | Optional. Possible values:
|
Note: If the array have string keys, the returned array will allways preserve the keys. (See example 4)
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2)); ?> |
The output of the code above will be:
Array ( [0] => Cat [1] => Horse ) |
With a negative start parameter:
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,-2,1)); ?> |
The output of the code above will be:
Array ( [0] => Horse ) |
With the preserve parameter set to true:
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2,true)); ?> |
The output of the code above will be:
Array ( [1] => Cat [2] => Horse ) |
With string keys:
<?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird"); print_r(array_slice($a,1,2)); ?> |
The output of the code above will be:
Array ( [b] => Cat [c] => Horse ) |
From http://www.w3schools.com (Copyright Refsnes Data)