PHP array_slice() Function
Complete PHP Array Reference
Definition and Usage
The array_slice() function returns selected parts of an array.
Syntax
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:- true - Preserve keys
- false -
Default - Reset keys
|
Tips and Notes
Note: If the array have string keys, the returned array will allways preserve the keys.
(See example 4)
Example 1
<?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 )
|
Example 2
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:
Example 3
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 )
|
Example 4
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 )
|
Complete PHP Array Reference
Learn XML with Stylus Studio XML Tools - Free Download!
 |
|
Stylus Studio makes it easy to edit and validate XML, XSLT, DTD, XML Schema, XHTML, XPath, XQuery and Web Service applications.
Free XML video demonstrations will help you learn XML and become a W3C XML development master in just minutes!
Download a FREE Trial Now!
|
|