PHP array_slice () function
Examples
Remove the start from the second element of the array, and returns all the elements until the end of the array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Running instance »
Definition and Usage
array_slice () function returns an array of selected portions.
NOTE: If thearray has a string key name, the returned array will retain the key name (see Example 4).
grammar
array_slice( array,start,length,preserve )
参数 | 描述 |
---|---|
array | 必需。规定数组。 |
start | 必需。数值。规定取出元素的开始位置。
0 = 第一个元素。
如果该值设置为正数,则从前往后开始取。如果该值设置为负数,则从后向前取 start 绝对值。
-2 意味着从数组的倒数第二个元素开始。 |
length | 可选。数值。规定被返回数组的长度。
如果该值设置为整数,则返回该数量的元素。如果该值设置为负数,则函数将在举例数组末端这么远的地方终止取出。如果该值未设置,则返回从 start 参数设置的位置开始直到数组末端的所有元素。
|
preserve | 可选。规定函数是保留键名还是重置键名。可能的值:
|
technical details
return value: | Returns an array of selected portions. |
---|---|
PHP version: | 4+ |
Update log: | preserve parameter is added in PHP 5.0.2 in. |
More examples
Example 1
Start removing from the first element of the array, and returns two elements:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Running instance »
Example 2
Use a negative start parameter:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Running instance »
Example 3
With set preserve the true parameters:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Running instance »
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));
?>
$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));
?>
Running instance »
Complete PHP Array Reference