从第三个数组元素开始切片,并返回数组中的其余元素:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
亲自试一试 »
array_slice() 函数返回数组的选定部分。
笔记:如果数组有字符串键,则返回的数组将始终保留键(参见示例 4)。
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. Specifies if the function should preserve or reset the keys. Possible values:
|
返回值: | 返回数组的选定部分 |
---|---|
PHP 版本: | 4+ |
PHP 变更日志: | 这个保存PHP 5.0.2 中添加了参数 |
从第二个数组元素开始切片,并仅返回两个元素:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
亲自试一试 »
使用负启动参数:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
亲自试一试 »
将 keep 参数设置为 true 时:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
亲自试一试 »
使用字符串和整数键:
<?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));
?>
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!