array_splice
(PHP 4, PHP 5, PHP 7, PHP 8)
array_splice — 去掉陣列中的某一部分並用其它值取代
說明
把 array 陣列中由
offset 和 length
指定的單元去掉,如果提供了 replacement 參數,則用其中的單元取代。
注意:
array中的數字鍵名不被保留。
注意: 如果
replacement不是陣列,會被 型別轉換 成陣列 (例如:(array) $replacement)。 當傳入的replacement是個對像或者null,會導致未知的行為出現。
參數
-
array -
輸入的陣列。
-
offset -
如果
offset為正,則從array陣列中該值指定的偏移量開始移除。如果
offset為負,則從array末尾倒數該值指定的偏移量開始移除。 -
length -
如果省略
length,則移除陣列中從offset到結尾的所有部分。如果指定了
length並且為正值,則移除這麼多單元。如果指定了
length並且為負值,則移除部分停止於陣列末尾該數量的單元。如果設定了
length為零,不會移除單元。小技巧當給出了
replacement時要移除從offset到陣列末尾所有單元時,用count($input)作為length。 -
replacement -
如果給出了
replacement陣列,則被移除的單元被此陣列中的單元替代。如果
offset和length的組合結果是不會移除任何值,則replacement陣列中的單元將被插入到offset指定的位置。注意:
不保留替換陣列
replacement中的鍵名。如果用來替換
replacement只有一個單元,那麼不需要給它加上array()或方括號,除非該單元本身就是一個陣列、一個對像或者null。
返回值
返回一個包含有被移除單元的陣列。
更新日誌
| 版本 | 說明 |
|---|---|
| 8.0.0 |
length 現在可為空(nullable)。
|
範例
示例 #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"
}
示例 #2 幾個以不同表達式實現相同效果的 array_splice() 例子
以下表達式是相同的:
<?php
// 新增兩個新元素到 $input
array_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);
?>