Php/docs/function.array-splice
array_splice
(PHP 4, PHP 5, PHP 7)
array_splice — 去掉数组中的某一部分并用其它值取代
说明
array_splice
( array &$input
, int $offset
[, int $length = count($input)
[, mixed $replacement = array()
]] ) : array
把 input 数组中由
offset 和 length
指定的单元去掉,如果提供了 replacement 参数,则用其中的单元取代。
Note:
input中的数字键名不被保留。
Note:
如果
replacement不是数组,会被 类型转换 成数组 (例如:(array) $replacement)。 当传入的replacement是个对象或者null,会导致未知的行为出现。
参数
input输入的数组。
offset如果
offset为正,则从input数组中该值指定的偏移量开始移除。如果
offset为负,则从input末尾倒数该值指定的偏移量开始移除。length如果省略
length,则移除数组中从offset到结尾的所有部分。如果指定了
length并且为正值,则移除这么多单元。如果指定了
length并且为负值,则移除部分停止于数组末尾该数量的单元。如果设置了
length为零,不会移除单元。Tip
当给出了
replacement时要移除从offset到数组末尾所有单元时,用count($input)作为length。replacement如果给出了
replacement数组,则被移除的单元被此数组中的单元替代。如果
offset和length的组合结果是不会移除任何值,则replacement数组中的单元将被插入到offset指定的位置。Note:
不保留替换数组
replacement中的键名。如果用来替换
replacement只有一个单元,那么不需要给它加上array()或方括号,除非该单元本身就是一个数组、一个对象或者null。
返回值
返回一个包含有被移除单元的数组。
范例
Example #1 array_splice() 例子
<?php$input = array("red", "green", "blue", "yellow");array_splice($input, 2);var_dump($input);$input = array("red", "green", "blue", "yellow");array_splice($input, 1, -1);var_dump($input);$input = array("red", "green", "blue", "yellow");array_splice($input, 1, count($input), "orange");var_dump($input);$input = array("red", "green", "blue", "yellow");array_splice($input, -1, 1, array("black", "maroon"));var_dump($input);?>
以上例程会输出:
array(2) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(6) "yellow"
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(6) "orange"
}
array(5) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
[3]=>
string(5) "black"
[4]=>
string(6) "maroon"
}
Example #2 几个以不同表达式实现相同效果的 array_splice() 例子
以下表达式是相同的:
<?php// 添加两个新元素到 $inputarray_push($input, $x, $y);array_splice($input, count($input), 0, array($x, $y));// 移除 $input 中的最后一个元素array_pop($input);array_splice($input, -1);// 移除 $input 中第一个元素array_shift($input);array_splice($input, 0, 1);// 在 $input 的开头插入一个元素array_unshift($input, $x, $y);array_splice($input, 0, 0, array($x, $y));// 在 $input 的索引 $x 处替换值$input[$x] = $y; // 对于键名和偏移量等值的数组array_splice($input, $x, 1, $y);?>