php method to delete duplicate values in an array: 1. Use array_unique() function, syntax "array_unique(array)". 2. First use the array_flip() function to reverse the keys and values of the array and remove duplicate values; then use array_flip() to reverse the array back.
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php deletes duplicates in the array Element value
Method 1: Directly use the array_unique() function
<?php $arr1 = array("a" => "green", "b" => "red", "c" => "green", "d" => "blue","e" => "red"); var_dump($arr1); $arr2 = array_unique($arr1); var_dump($arr2); ?>
Output:
array (size=5) 'a' => string 'green' (length=5) 'b' => string 'red' (length=3) 'c' => string 'green' (length=5) 'd' => string 'blue' (length=4) 'e' => string 'red' (length=3) array (size=3) 'a' => string 'green' (length=5) 'b' => string 'red' (length=3) 'd' => string 'blue' (length=4)
Instructions:
array_unique() function is used to remove duplicate values from an array. If two or more array values are the same, only the first value is retained and the other values are removed.
Note: The retained array will retain the key type of the first array item.
Syntax
array_unique(array)
Method 2: Use the array_flip() function twice
<?php header("content-type:text/html;charset=utf-8"); $arr = array("a" => "green", "b" => "red", "c" => "green", "d" => "blue","e" => "red"); // 输出原始数组 echo "原始数组 :"; var_dump($arr); // 通过使用翻转键和值移除重复值 $arr = array_flip($arr); // 通过再次翻转键和值来恢复数组元素 $arr = array_flip($arr); // 重新排序数组键 $arr = array_values($arr); // 输出更新后的数组 echo "更新数组 :"; var_dump($arr); ?>
Output:
原始数组 : array (size=5) 'a' => string 'green' (length=5) 'b' => string 'red' (length=3) 'c' => string 'green' (length=5) 'd' => string 'blue' (length=4) 'e' => string 'red' (length=3) 更新数组 : array (size=3) 0 => string 'green' (length=5) 1 => string 'red' (length=3) 2 => string 'blue' (length=4)
Explanation:
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 after the reversal Keep the last key and value, and use this feature to indirectly achieve duplication of the array.
Grammar
array_flip(array);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete duplicate element values in an array in php. For more information, please follow other related articles on the PHP Chinese website!