PHP array_slice() 函数
实例
从数组的第二个元素开始取出,并返回直到数组末端的所有元素:
<?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));
?>
运行实例 »
定义和用法
array_slice() 函数返回数组中的选定部分。
注释:如果数组有字符串键名,所返回的数组将保留键名(参见实例 4)。
语法
array_slice(array,start,length,preserve)
参数 | 描述 |
---|---|
array | 必需。规定数组。 |
start | 必需。数值。规定取出元素的开始位置。
0 = 第一个元素。
如果该值设置为正数,则从前往后开始取。如果该值设置为负数,则从后向前取 start 绝对值。
-2 意味着从数组的倒数第二个元素开始。 |
length | 可选。数值。规定被返回数组的长度。
如果该值设置为整数,则返回该数量的元素。如果该值设置为负数,则函数将在举例数组末端这么远的地方终止取出。如果该值未设置,则返回从 start 参数设置的位置开始直到数组末端的所有元素。
|
preserve | 可选。规定函数是保留键名还是重置键名。可能的值:
|
技术细节
返回值: | 返回数组中的选定部分。 |
---|---|
PHP 版本: | 4+ |
更新日志: | preserve 参数是在 PHP 5.0.2 中新增的。 |
更多实例
实例 1
从数组的第一个元素开始取出,并返回两个元素:
<?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));
?>
运行实例 »
实例 2
使用负的 start 参数:
<?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));
?>
运行实例 »
实例 3
带有设置为 true 的 preserve 参数:
<?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));
?>
运行实例 »
实例 4
带有字符串和整数键名:
<?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));
?>
运行实例 »
完整的 PHP Array 参考手册
点我分享笔记