`array_unshift()` 在陣列**開頭插入一或多個元素**,數字鍵名**重新索引從 0 開始**,字符串鍵名保持不變。返回新陣列長度。本文說明語法、批量插入、鍵名行為、效能與替代方案。
int array_unshift ( array &$array, mixed $value1 [, mixed $... ] )
<?php
$alpha = ['a', 'b', 'c'];
$count = array_unshift($alpha, 'd', 'e');
print_r($alpha);
// Array ( [0] => d [1] => e [2] => a [3] => b [4] => c )
echo "新長度: $count"; // 5
// 關聯陣列
$assoc = ['x' => 1, 'y' => 2];
array_unshift($assoc, 'new');
// Array ( [0] => new [1] => 1 [2] => 2 ) 原鍵名 x,y 變為數字索引!
?>
**重要**:`array_unshift` 會將**所有數字鍵名重建**,且**字符串鍵名也會轉為數字索引**!這與 `array_shift` 不同(shift 保持字符串鍵)。
$test = ['a' => 'A', 'b' => 'B'];
array_unshift($test, 'X');
// 結果:[0 => 'X', 1 => 'A', 2 => 'B'] 字符串鍵 'a','b' 消失!
同 `array_shift`,需將現有元素向後移動,**大陣列頻繁 unshift 會極慢**。
| 需求 | 方案 | 複雜度 |
|---|---|---|
| 首部插入、尾部刪除 (隊列) | `SplQueue` : `enqueue`/`dequeue` | O(1) |
| 雙端隊列 (首尾皆可增減) | `SplDoublyLinkedList` | O(1) |
| 固定陣列需邏輯首部 | 維護 `$offset` 指標,邏輯上視為首部 | O(1) |
| 小陣列、單次操作 | `array_unshift` 可接受 | O(n) |
<?php
$dll = new SplDoublyLinkedList();
$dll->push('tail1'); // 尾部插入
$dll->unshift('head1'); // 首部插入
$dll->push('tail2');
$dll->unshift('head2');
foreach ($dll as $v) {
echo "$v\n"; // head2, head1, tail1, tail2
}
?>
| 函數 | 位置 | 參數 | 返回 | 鍵名影響 |
|---|---|---|---|---|
| array_unshift | 首部 | 多個值 | 新長度 | 所有鍵重建為數字索引 |
| array_push | 尾部 | 多個值 | 新長度 | 不影響鍵名 |
| array_shift | 首部 | 無 | 移除值 | 數字鍵重建,字符串鍵保持 |
| array_pop | 尾部 | 無 | 移除值 | 不影響鍵名 |
掌握 `array_unshift` 鍵名重建特性與效能邊界,能正確選擇陣列操作策略,避免數據結構破壞與效能問題。