(PHP 4, PHP 5)
array_splice — 把數組中的一部分去掉并用其它值取代
說明
array array_splice ( array&$input
, int $offset
[, int $length
= 0
[, mixed $replacement
]] )
把 input
數組中由
offset
和 length
指定的單元去掉,如果提供了 replacement
參數,則用其中的單元取代。
注意
input
中的數字鍵名不被保留。
Note:
If replacement
is not an array, it will be
typecast
to one (i.e. (array) $parameter
). This may result in unexpected
behavior when using an object or NULL
replacement
.
參數
input
輸入的數組。
offset
如果 offset
為正,則從 input
數組中該值指定的偏移量開始移除。如果 offset
為負,則從 input
末尾倒數該值指定的偏移量開始移除。
length
如果省略 length
,則移除數組中從 offset
到結尾的所有部分。如果指定了 length
并且為正值,則移除這么多單元。如果指定了 length
并且為負值,則移除從 offset
到數組末尾倒數
length
為止中間所有的單元。小竅門:當給出了
replacement
時要移除從 offset
到數組末尾所有單元時,用 count($input) 作為 length
。
replacement
如果給出了 replacement
數組,則被移除的單元被此數組中的單元替代。
如果
offset
和 length
的組合結果是不會移除任何值,則 replacement
數組中的單元將被插入到 offset
指定的位置。 注意替換數組中的鍵名不保留。
如果用來替換 replacement
只有一個單元,那么不需要給它加上
array(),除非該單元本身就是一個數組、一個對象或者 NULL
。
返回值
返回一個包含有被移除單元的數組。
范例
Example #1 array_splice() 例子
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// "blue", "black", "maroon")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// "blue", "purple", "yellow");
?>
Example #2 array_splice() 例子
以下表達式以同樣方式修改了 $input:
<?php
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
array_pop($input);
array_splice($input, -1);
array_shift($input);
array_splice($input, 0, 1);
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
$input[$x] = $y; // 對于鍵名和偏移量等值的數組
array_splice($input, $x, 1, $y);
?>
參見
array_slice() - 從數組中取出一段 unset() - 釋放給定的變量 array_merge() - 合并一個或多個數組