| 特性 | array_merge() | + 運算子 |
|---|---|---|
| 數字索引 | 重新索引 (0,1,2...) | 保留原索引,後者不覆蓋前者 |
| 字串鍵名 | 後者覆蓋前者 | 前者優先,後者忽略 |
| 回傳值 | 新陣列 | 新陣列 |
| 參數數量 | 任意多個 | 僅兩個 |
| NULL 參數 | PHP 7.4+ 拋出 TypeError | 視為空陣列 |
<?php
$r = [1,2,3,4,5,6]; // 索引 0-5
$e = [7,8,9,10]; // 索引 0-3
// array_merge:附加在後,重新索引
print_r(array_merge($r, $e));
/* Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7 ← 續接
[7] => 8
[8] => 9
[9] => 10
)
*/
// + 運算子:索引衝突,後者被忽略
print_r($r + $e);
/* Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6 ← $e 的 0-3 索引衝突,全被捨棄
)
*/
<?php
$r = ['r' => 1, 2, 3, 4, 5, 6]; // 'r' => 1, 0=>2, 1=>3...
$e = ['r' => 7, 8, 9, 10]; // 'r' => 7, 0=>8, 1=>9...
// array_merge:字串鍵 'r' 後者覆蓋,數字索引重新編排
print_r(array_merge($r, $e));
/* Array
(
[r] => 7 ← 覆蓋
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
[5] => 8 ← $e 的數字索引重新編排
[6] => 9
[7] => 10
)
*/
// + 運算子:'r' 保留首值 (1),數字索引 0-5 衝突,後者忽略
print_r($r + $e);
/* Array
(
[r] => 1 ← 保留首值
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
)
*/
$config = array_merge($defaults, $userConfig);$options = $userOptions + $defaults; (用戶設定優先)array_merge(null) 錯誤<?php
function array_merge_recursive_distinct(array &$a1, array &$a2) {
foreach ($a2 as $key => &$value) {
if (is_array($value) && isset($a1[$key]) && is_array($a1[$key])) {
array_merge_recursive_distinct($a1[$key], $value);
} else {
$a1[$key] = $value;
}
}
return $a1;
}
$default = ['db' => ['host' => 'localhost', 'port' => 3306], 'debug' => false];
$user = ['db' => ['host' => 'db.example.com'], 'cache' => true];
$result = array_merge_recursive_distinct($default, $user);
/*
['db' => ['host' => 'db.example.com', 'port' => 3306], 'debug' => false, 'cache' => true]
*/
<?php
// 使用 + 但先重新索引第二個陣列
function mergePreserveKeys(array $a, array $b): array {
$maxKey = $a ? max(array_keys($a)) : -1;
$bReindexed = [];
foreach ($b as $k => $v) {
$bReindexed[++$maxKey] = $v;
}
return $a + $bReindexed;
}
$a = [0 => 'a', 5 => 'b'];
$b = [10, 20];
print_r(mergePreserveKeys($a, $b));
// [0=>'a', 5=>'b', 6=>10, 7=>20]
<?php
$a = [1, 2];
$b = [3, 4];
$merged = [...$a, ...$b]; // [1, 2, 3, 4] 等同 array_merge
// 關聯陣列解構 (後者覆蓋)
$c = ['x' => 1];
$d = ['x' => 2, 'y' => 3];
$merged = [...$c, ...$d]; // ['x' => 2, 'y' => 3]
<?php
$big1 = range(1, 100000);
$big2 = range(100001, 200000);
$start = microtime(true);
$r1 = array_merge($big1, $big2);
echo "array_merge: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
$r2 = $big1 + $big2; // 索引衝突,結果僅 $big1
echo "+ operator: " . (microtime(true) - $start) . "s\n";
/* 典型結果:
array_merge: 0.008s
+ operator: 0.001s (快但語意不同)
*/
需要合併陣列 ├─ 超過 2 個陣列? → array_merge() ├─ 需重新索引數字鍵? → array_merge() ├─ 需覆蓋字串鍵 (配置合併)? → array_merge() ├─ 需保留首值、忽略後者 (預設值填充)? → + 運算子 ├─ 僅 2 個陣列、不想處理 NULL? → + 運算子 └─ 深度合併巢狀陣列? → 自訂遞迴函數
理解兩者語意差異,能避免「配置被意外覆蓋」或「列表索引錯亂」等隱蔽 Bug。