陣列集合運算是資料處理高頻需求:找共同元素 (交集)、找差異元素 (差集)。PHP 提供四組核心函數,分別針對「僅比較值」與「比較鍵+值」兩種語意。本文系統整理 array_intersect、array_intersect_assoc、array_diff、array_diff_assoc 的行為差異、參數說明、實戰範例與常見陷阱。
| 函數 | 比較依據 | 返回內容 | 鍵名保留 |
|---|---|---|---|
array_intersect | 值 | 所有陣列中都出現的值 | ✅ 保留第一個陣列的鍵 |
array_intersect_assoc | 鍵 + 值 | 所有陣列中鍵值都相同的對 | ✅ 保留 |
array_diff | 值 | 第一個陣列有、其他陣列沒有的值 | ✅ 保留第一個陣列的鍵 |
array_diff_assoc | 鍵 + 值 | 第一個陣列有、其他陣列鍵值不全同的對 | ✅ 保留 |
array_intersect()$fruit1 = ["Apple", "Banana", "Orange"]; $fruit2 = ["Pear", "Apple", "Grape"]; $fruit3 = ["Watermelon", "Orange", "Apple"]; $intersection = array_intersect($fruit1, $fruit2, $fruit3); print_r($intersection); // Array ( [0] => Apple ) ← 只有 Apple 在三個陣列都出現 // 鍵名保留自 $fruit1 (索引 0)
array_intersect_assoc()$fruit1 = ["red"=>"Apple", "yellow"=>"Banana", "orange"=>"Orange"]; $fruit2 = ["yellow"=>"Pear", "red"=>"Apple", "purple"=>"Grape"]; $fruit3 = ["green"=>"Watermelon", "orange"=>"Orange", "red"=>"Apple"]; $intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3); print_r($intersection); // Array ( [red] => Apple ) ← 只有 red=>Apple 三個陣列完全相同 // yellow=>Banana/Pear 值不同;orange=>Orange 只有 fruit1/3 有
array_diff()$fruit1 = ["Apple", "Banana", "Orange"]; $fruit2 = ["Pear", "Apple", "Grape"]; $fruit3 = ["Watermelon", "Orange", "Apple"]; $diff = array_diff($fruit1, $fruit2, $fruit3); print_r($diff); // Array ( [1] => Banana ) ← 只有 Banana 獨佔於 $fruit1 // 鍵名 1 保留自 $fruit1
array_diff_assoc()$fruit1 = ["red"=>"Apple", "yellow"=>"Banana", "orange"=>"Orange"]; $fruit2 = ["yellow"=>"Pear", "red"=>"Apple", "purple"=>"Grape"]; $fruit3 = ["green"=>"Watermelon", "orange"=>"Orange", "red"=>"Apple"]; $diff = array_diff_assoc($fruit1, $fruit2, $fruit3); print_r($diff); // Array ( [yellow] => Banana ) // red=>Apple 三個都有;orange=>Orange 在 fruit1/3 有;yellow=>Banana 只在 fruit1 (fruit2 是 Pear)
"1" === 1 為 false。array_intersect([1], ["1"]) 返回空陣列。需先統一型別 (如 array_map('intval', $arr))。array_intersect_assoc **要求鍵名完全相同**。[0=>'a'] 與 ['0'=>'a'] (字串鍵 vs 整數鍵) 視為不同。array_intersect($a, $b, $c, $d...),邏輯為「第一個陣列的元素,在**所有**其他陣列中都存在」。array_flip 轉鍵值或使用 array_keys + array_intersect_key 以鍵名運算加速。array_intersect_key():僅比較**鍵名**,忽略值。array_diff_key():僅比較**鍵名**差異。array_uintersect() / array_udiff():自訂**值比較回呼函數** (如大小寫不敏感、物件比較)。array_uintersect_assoc() / array_udiff_assoc():自訂值比較 + 鍵名比較。array_intersect_uassoc() / array_diff_uassoc():自訂**鍵名比較回呼函數**。熟練掌握這組集合運算函數,能以聲明式、可讀性高的代碼替代繁瑣的迴圈判斷,大幅提升資料處理開發效率與正確性。