Home >Backend Development >PHP Tutorial >How to remove duplicate elements from array in PHP
In PHP, you can use the built-in function "array_unique()" to directly delete duplicate elements, or you can use the "array_flip()" function to indirectly delete duplicate elements.
【Video tutorial recommendation: PHP tutorial】
array_unique() function
array_unique() function can remove duplicate values in the array and return the result array; when the values of several array elements are equal, only the first element is retained, and the other elements are delete.
Code example:
<?php $result1 = array("a" => "green", "red", "b" => "green", "blue", "red"); var_dump($result1); $result2 = array_unique($result1); var_dump($result2); ?>
Output:
##array_flip() function
array_flip() is a function that reverses the keys and values of an array. It has a characteristic that if two values in the array are the same, then the last key and value will be retained after the reversal. Use We use this feature to indirectly implement array deduplication.<?php header("content-type:text/html;charset=utf-8"); $a = array(1, 5, 2, 5, 1, 3, 2, 4, 5); // 输出原始数组 echo "原始数组 :"; var_dump($a); // 通过使用翻转键和值移除重复值 $a = array_flip($a); // 通过再次翻转键和值来恢复数组元素 $a = array_flip($a); // 重新排序数组键 $a = array_values($a); // 输出更新后的数组 echo "更新数组 :"; var_dump($a); ?>Output:
The above is the detailed content of How to remove duplicate elements from array in PHP. For more information, please follow other related articles on the PHP Chinese website!