Home  >  Article  >  Backend Development  >  How to see duplicate values ​​in array in php

How to see duplicate values ​​in array in php

PHPz
PHPzOriginal
2023-04-23 10:10:43841browse

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:

 $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:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn