| 特性 | unset() | array_splice() |
|---|---|---|
| 鍵值重組 | ❌ 保留原鍵值,產生「洞」 | ✅ 重新索引 (0,1,2...) |
| 回傳值 | 無 | 被移除的元素陣列 |
| 多元素刪除 | 需迴圈 | 單次呼叫支援長度參數 |
| 關聯陣列適用 | ✅ 適合 | ⚠️ 會重置數字鍵,字串鍵保留 |
$colors = ["red", "green", "blue", "yellow"];
unset($colors[1]); // 刪除 "green"
var_dump($colors);
/*
array(3) {
[0]=> "red"
[2]=> "blue" // 鍵值跳號!
[3]=> "yellow"
}
*/
echo $colors[2]; // "blue" - 非直覺
echo $colors[1]; // Notice: Undefined offset
$colors = array_values($colors); // 重建 0,1,2 索引
// 或
$colors = array_merge($colors); // 同效果
$colors = ["red", "green", "blue", "yellow"];
$removed = array_splice($colors, 1, 1); // 從索引 1 刪除 1 個
var_dump($colors); // ["red", "blue", "yellow"] - 索引重組為 0,1,2
var_dump($removed); // ["green"] - 回傳被刪除元素
$arr = [1, 2, 3, 4];
// 刪除索引 1-2,插入新元素
array_splice($arr, 1, 2, ['a', 'b', 'c']);
// 結果:[1, 'a', 'b', 'c', 4]
unset($arr[$key])array_splice()array_splice()array_splice()小型陣列差異微乎其微。大型陣列 (10萬+) 時,array_splice() 需重建陣列較慢,若頻繁刪除建議考慮資料結構調整或使用 SplFixedArray。