(PHP 4, PHP 5, PHP 7, PHP 8)
array_splice — 去掉數組中的某一部分并用其它值取代
把 array
數組中由
offset
和 length
指定的單元去掉,如果提供了 replacement
參數,則用其中的單元取代。
注意:
array
中的數字鍵名不被保留。
注意: 如果
replacement
不是數組,會(huì )被 類(lèi)型轉換 成數組 (例如:(array) $replacement
)。 當傳入的replacement
是個(gè)對象或者null
,會(huì )導致未知的行為出現。
array
輸入的數組。
offset
如果 offset
為正,則從 array
數組中該值指定的偏移量開(kāi)始移除。
如果 offset
為負,則從 array
末尾倒數該值指定的偏移量開(kāi)始移除。
length
如果省略 length
,則移除數組中從 offset
到結尾的所有部分。
如果指定了 length
并且為正值,則移除這么多單元。
如果指定了 length
并且為負值,則移除部分停止于數組末尾該數量的單元。
如果設置了 length
為零,不會(huì )移除單元。
當給出了
replacement
時(shí)要移除從 offset
到數組末尾所有單元時(shí),用 count($input)
作為 length
。
replacement
如果給出了 replacement
數組,則被移除的單元被此數組中的單元替代。
如果
offset
和 length
的組合結果是不會(huì )移除任何值,則 replacement
數組中的單元將被插入到 offset
指定的位置。
注意:
不保留替換數組
replacement
中的鍵名。
如果用來(lái)替換 replacement
只有一個(gè)單元,那么不需要給它加上
array()
或方括號,除非該單元本身就是一個(gè)數組、一個(gè)對象或者 null
。
返回一個(gè)包含有被移除單元的數組。
版本 | 說(shuō)明 |
---|---|
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);
?>
以上例程會(huì )輸出:
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 幾個(gè)以不同表達式實(shí)現相同效果的 array_splice() 例子
以下表達式是相同的:
<?php
// 添加兩個(gè)新元素到 $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
// 移除 $input 中的最后一個(gè)元素
array_pop($input);
array_splice($input, -1);
// 移除 $input 中第一個(gè)元素
array_shift($input);
array_splice($input, 0, 1);
// 在 $input 的開(kāi)頭插入一個(gè)元素
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
// 在 $input 的索引 $x 處替換值
$input[$x] = $y; // 對于鍵名和偏移量等值的數組
array_splice($input, $x, 1, $y);
?>