使用 array_unique() 移除陣列重複值時,該函數保留原有鍵名,導致結果陣列索引不連續。若直接使用 for 迴圈配合 count() 遍歷,將遺漏元素。
$test_array = array(1,2,3,4,4,5,5,6);
$test_array_unique = array_unique($test_array);
// 結果:Array ( [0]=>1 [1]=>2 [2]=>3 [3]=>4 [5]=>5 [7]=>6 )
// 索引 4、6 被刪除元素佔用,實際元素只有 6 個,但最大索引為 7
for($i=0; $i<count($test_array_unique); $i++) {
echo $test_array_unique[$i];
}
// 輸出:12345 (遺漏了索引 7 的值 6)
array_values() 重建索引array_values() 返回陣列所有值並重新建立 0 起始的連續數字索引,完美解決遍歷問題。
$test_array = array(1,2,3,4,4,5,5,6);
$test_array_unique = array_values(array_unique($test_array));
// 結果:Array ( [0]=>1 [1]=>2 [2]=>3 [3]=>4 [4]=>5 [5]=>6 )
for($i=0; $i<count($test_array_unique); $i++) {
echo $test_array_unique[$i];
}
// 輸出:123456 (完整輸出所有元素)
array_unique() 對關聯陣列同樣保留鍵名。若需重置為數字索引,同樣套用 array_values():
$assoc = array('a'=>1, 'b'=>2, 'c'=>1, 'd'=>3);
$unique = array_values(array_unique($assoc));
// 結果:Array ( [0]=>1 [1]=>2 [2]=>3 )
array_unique() 時間複雜度 O(n log n),大型陣列(>10萬元素)可能較慢。array_flip(array_flip($arr)) 技巧(僅適用純值陣列),速度更快。array_unique() 有顯著效能優化。$unique = array_unique($arr);$result = array_values($unique);$result = array_values(array_unique($arr));foreach 避免索引問題,foreach($result as $val) 最安全簡潔。記住:去重後必須重建索引才能安全使用數字索引遍歷,這是 PHP 陣列操作中極易踩坑的細節。