|
array_splice (PHP 4, PHP 5) array_splice --
把陣列中的一部分去掉並用其它值取代
說明array array_splice ( array &input, int offset [, int length [, array replacement]] )
array_splice() 把 input 陣列中由
offset 和 length
特殊的單元去掉,若果提供了 replacement 參數,則用
replacement
陣列中的單元取代。返回一個包括有被移除單元的陣列。注意
input 中的數字鍵名不被保留。
若果 offset 為正,則從 input
陣列中該值特殊的偏移量開始移除。若果 offset
為負,則從 input 末尾倒數該值特殊的偏移量開始移除。
若果省略 length,則移除陣列中從 offset
到結尾的所有部分。若果指定了 length
並且為正值,則移除這麼多單元。若果指定了 length
並且為負值,則移除從 offset 到陣列末尾倒數
length 為止中間所有的單元。小竅門:當給出了
replacement 時要移除從 offset
到陣列末尾所有單元時,用 count($input) 作為 length。
若果給出了 replacement 陣列,則被移除的單元被此陣列中的單元替代。若果
offset 和 length
的組合結果是不會移除任何值,則 replacement
陣列中的單元將被插入到 offset
特殊的位置。注意置換陣列中的鍵名不保留。若果用來置換的值只是一個單元,那麼不需要給它加上
array(),除非該單元本身就是一個陣列。
以下表達式以同樣模式修改了 $input:
表格 1. array_splice() 等價表達式
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)
|
返回一個包括被移除單元的陣列。
例子 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"); ?>
|
|
參見 array_slice(),unset()
和 array_merge()。
| |