目录

PHP array_slice() 函数

❮ PHP 数组参考

示例

从第三个数组元素开始切片,并返回数组中的其余元素:

<?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:
  • true - Preserve keys
  • false - Default. Reset keys


技术细节

返回值: 返回数组的选定部分
PHP 版本: 4+
PHP 变更日志: 这个保存PHP 5.0.2 中添加了参数

更多示例

示例1

从第二个数组元素开始切片,并仅返回两个元素:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
亲自试一试 »

示例2

使用负启动参数:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
亲自试一试 »

示例3

将 keep 参数设置为 true 时:

<?php
$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));
?>
亲自试一试 »

❮ PHP 数组参考