Home > Article > Backend Development > How to see duplicate values in array in php
In PHP, we can use some built-in functions to find duplicate values in an array. The most commonly used method is the array_count_values() function, which is used to count the number of occurrences of each element in the array.
The sample code is as follows:
<?php $array = array(1, 2, 3, 3, 4, 4, 4, 5); //计算数组中每个元素出现的次数 $counts = array_count_values($array); //输出所有出现过重复的值 foreach ($counts as $value => $count) { if ($count > 1) { echo "$value 出现了 $count 次\n"; } } ?>
The output result is:
3 出现了 2 次 4 出现了 3 次
In the above code, we first define the array containing repeated elements as $array, and then use array_count_values() The function counts the number of occurrences of each element and stores the results in the $counts array.
Next, we traverse the $counts array. If the number of occurrences of an element is greater than 1, it means that the element has been repeated. We can use the echo statement to output the element and the number of times it appears.
In addition to the array_count_values() function, we can also use the array_unique() function in combination with the array_diff_assoc() function to find duplicate values in the array. The specific implementation method is as follows:
<?php $array = array(1, 2, 3, 3, 4, 4, 4, 5); //使用array_unique()函数去重得到新数组 $unique = array_unique($array); //使用array_diff_assoc()函数得到数组中重复的元素 $repeats = array_diff_assoc($array, $unique); //输出所有出现过重复的值 foreach ($repeats as $value) { echo "$value 出现了重复\n"; } ?>
The output result is:
3 出现了重复 4 出现了重复 4 出现了重复
In the above code, we first use the array_unique() function to deduplicate the array and obtain a new array that does not contain duplicate elements. Then, we use the array_diff_assoc() function to get an array $repeats containing repeated elements.
Finally, we traverse the $repeats array and output the value of each repeated element.
In summary, there are many ways to find duplicate values in an array in PHP. The two methods demonstrated above are relatively common methods. Depending on the scenario and needs, different methods can be chosen to implement it.
The above is the detailed content of How to see duplicate values in array in php. For more information, please follow other related articles on the PHP Chinese website!