Home > Article > Backend Development > How to remove duplicate elements from an array in php
Array is one of the most commonly used data types in PHP. However, sometimes we need to remove duplicate elements from an array. This article will introduce you how to delete duplicate elements from an array using PHP language.
1. Use PHP’s array_unique function
PHP provides a built-in function array_unique, which is used to delete all duplicate elements in the array. Using this function is very simple, just pass an array to the function.
The following is an example:
$array = array(1,2,2,3,3,3,4,4,4,4); $array = array_unique($array); print_r($array);
The output result of the above example is:
Array ( [0] => 1 [1] => 2 [3] => 3 [6] => 4 )
2. Use a loop to delete duplicate elements in the array
Another alternative The method is to remove duplicate elements from the array through a loop. This method takes into account each element in the array and removes it if it already appears in the array. Although this method is more cumbersome, it can handle arrays more flexibly.
The following is an example:
$array = array(1,2,2,3,3,3,4,4,4,4); for($i=0; $i<count($array); $i++){ for($j=$i+1; $j<count($array); $j++){ if($array[$i] == $array[$j]){ array_splice($array,$j,1); $j--; } } } print_r($array);
The output result of the above example is the same as the first method:
Array ( [0] => 1 [1] => 2 [3] => 3 [6] => 4 )
3. Use PHP’s array_count_values function
Also There is a way to remove duplicate elements from an array, which uses PHP's array_count_values function. This function returns an associative array, the key is the unique element in the array, and the key value is the number of times the element appears in the array.
Therefore, we can pass the array to the array_count_values function, then use the array_keys function to extract the unique key names, and finally return a new array.
The following is an example:
$array = array(1,2,2,3,3,3,4,4,4,4); $count_array = array_count_values($array); $new_array = array_keys($count_array); print_r($new_array);
The output result of the above example is the same as the first method:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Summary
All three methods above can be used For removing duplicate elements from an array, the specific method you choose depends on your specific needs. Here, we introduced using PHP’s array_unique function, using a loop to remove duplicate elements in an array, and using PHP’s array_count_values function. These methods are three simple and effective ways to remove duplicate elements from an array in PHP.
The above is the detailed content of How to remove duplicate elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!