PHP array_slice()
Function
Complete PHP Array Reference Manual
Example
Extracts elements starting from the third element (index 2) and returns all elements until the end of the array:
<?php
$a = array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a, 2));
?>
Definition and Usage
The array_slice()
function returns the selected part of an array.
Note: If the array has string keys, the returned array will retain the keys (see Example 4).
Syntax
Parameter | Description |
---|---|
array | Required. Specifies the array. |
start | Required. Numeric. Specifies where to start the extraction. |
0 = the first element. If this value is set to a positive number, it starts from the beginning. If set to a negative number, it starts from the end counting backward. -2 means starting from the second last element. <br> | | length | Optional. Numeric. Specifies the length of the returned array. If set to a positive number, it returns that many elements. If set to a negative number, the function stops that far from the end of the array. If not set, it returns all elements from the start position to the end of the array. <br> | | preserve | Optional. Specifies whether the function should preserve the keys or reset them. Possible values: true - Preserve keys<br>false - <br> Default. Reset keys |
Technical Details
Return Value: | Returns the selected part of the array. |
---|---|
PHP Version: | 4+ |
--- | --- |
Changelog: | The preserve parameter was added in PHP 5.0.2. |
--- | --- |
More Examples
Example 1
Extracts the first element and returns two elements:
<?php
$a = array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a, 1, 2));
?>
Example 2
Using a negative start parameter:
<?php
$a = array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a, -2, 1));
?>
Example 3
With the preserve parameter set to true:
<?php
// Preserve keys set to true
$a = array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a, 1, 2, true));
// Do not preserve keys set to false (default)
$a = array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a, 1, 2, false));
// Note the keys are different in both arrays
?>
Example 4
With string 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));
?>