php array_slice 取出数组中的一段序列实例

php array_slice 函数在数组中根据条件取出一段值,并返回。如果数组有字符串键,所返回的数组将保留键名。本文章通过实例向大家讲解array_slice 函数的使用方法。

php array_slice — 从数组中取出一段

array_slice 函数基本语法:

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

参数介绍

参数 描述
array 必需。输入的数组。
soffset

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

如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

length

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

如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

preserve_keys

可选。规定函数是保留键名还是重置键名。可能的值:

  • true - 保留键名
  • false - 默认。重置键名

默认会重新排序并重置数组的数字索引。你可以通过将 preserve_keys 设为 TRUE 来改变此行为。 

返回值

返回其中一段。

实例:

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);  
print_r($output);echo "<br/><br/>";
$output = array_slice($input, -2, 1); 
print_r($output);echo "<br/><br/>";
$output = array_slice($input, 0, 3);  
print_r($output);echo "<br/><br/>";

print_r(array_slice($input, 2, -1));echo "<br/><br/>";
print_r(array_slice($input, 2, -1, true));
?> 

结果:

"; $output = array_slice($input, -2, 1); print_r($output);echo "

"; $output = array_slice($input, 0, 3); print_r($output);echo "

"; print_r(array_slice($input, 2, -1));echo "

"; print_r(array_slice($input, 2, -1, true)); ?>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!