Home >Backend Development >PHP Tutorial >PHP array deduplication of array elements_PHP tutorial
The simplest way is to use PHP's built-in function array_flip to achieve the deduplication effect. Another method is to use PHP's array_flip function to indirectly achieve the deduplication effect.
array_flip is a function that reverses the keys and values of the array. It has a characteristic that if two values in the array are the same, then the last key and
will be retained after inversion.value. Taking advantage of this feature, we use it to indirectly implement deduplication of arrays.
The code is as follows
|
Copy code
|
||||
$arr1 = array_flip($arr); print_r($arr1);//Reverse it first, remove duplicate values, and output Array ([a1] => d [b1] => b [a2] => c ) $arr2 = array_flip($arr); print_r($arr2);//Reverse it again to get the deduplicated array and output Array ([a1] => d [b1] => b [a2] => c ) $arr3 = array_unique($arr); print_r($arr3);//Use PHP’s array_unique function to remove duplicates and output Array ( [a] => a1 [b] => b1 [c] => a2 ) ?> |
User-defined function operation