PHP array_slice() 函数

实例

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

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

Run Instances

定义和用法

array_slice() 函数在数组中根据条件取出一段值,并返回。

注释:如果数组有字符串键,所返回的数组将保留键名。(参见例子 4)

语法

array_slice(array,start,length,preserve)
参数 描述
array 必需。规定数组。
start

必需。数值。规定取出元素的开始位置。 0 = 第一个元素。

如果该值设置为正数,则从前往后开始取。

如果该值设置为负数,则从后向前取 start 绝对值。 -2 意味着从数组的倒数第二个元素开始。

length

可选。数值。规定被返回数组的长度。

If this value is set to an integer, it returns the specified number of elements.

If this value is set to a negative number, the function will stop extracting at the end of the array so far from the end.

If this value is not set, it returns all elements from the start parameter position to the end of the array.

preserve

Optional. Specifies whether the function keeps or resets the keys. Possible values:

  • true - Keep keys
  • false - Default. Reset keys

Technical Details

Return Value: Returns the selected part of the array.
PHP Version: 4+
Update Log: Added in PHP 5.0.2 preserve Parameters.

More Examples

Example 1

Start from the second element of the array and return only two elements:

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

Run Instances

Example 2

using negative start Parameters:

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

Run Instances

Example 3

to preserve Parameter set to true:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>

Run Instances

Example 4

Handling String Keys 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));
?>

Run Instances