array_flip() 交換陣列鍵值,利用「鍵名不可重複」特性,雙重翻轉即可高效去重,效能約為 array_unique() 的 5 倍。
array array_flip(array $array): array
// 返回鍵值互換的新陣列,值必須為 int 或 string
原陣列: ['a' => 'x', 'b' => 'y', 'c' => 'x']
↓ array_flip()
中間態: ['x' => 'c', 'y' => 'b'] // 重複值 'x' 只保留最後一個鍵 'c'
↓ array_flip()
結果: ['c' => 'x', 'b' => 'y'] // 去重完成,保留最後出現的鍵
$arr = ['age' => 30, 'name' => '腳本之家', 'age' => 20];
// 實際上 PHP 陣列定義時重複鍵後者覆蓋前者
// 此處模擬值重複情況:
$arr = ['id1' => 'apple', 'id2' => 'banana', 'id3' => 'apple', 'id4' => 'orange'];
$unique = array_flip(array_flip($arr));
print_r($unique);
/*
Array
(
[id3] => apple // 保留最後出現的 apple
[id2] => banana
[id4] => orange
)
*/
$data = [];
for ($i = 0; $i < 100000; $i++) {
$data[] = rand(1, 10000); // 大量重複
}
$t1 = microtime(true);
$r1 = array_unique($data);
echo "array_unique: " . (microtime(true) - $t1) . " 秒\n"; // ~0.015s
$t2 = microtime(true);
$r2 = array_flip(array_flip($data));
echo "array_flip x2: " . (microtime(true) - $t2) . " 秒\n"; // ~0.003s
int 或 string,否則會觸發警告並跳過該元素array_reverse()array_values()$arr = ['a' => 1, 'b' => 2, 'c' => 1, 'd' => 3];
// 反轉 -> 去重 -> 反轉 會保留 'c' => 1
// 若要保留 'a' => 1:
$arr = array_reverse($arr, true); // 保留鍵名反轉
$arr = array_flip(array_flip($arr));
$arr = array_reverse($arr, true);