Home >Backend Development >PHP Problem >How to determine how many duplicate values there are in an array in php
Method: 1. Use the "$arr2=array_count_values($arr)" statement to count the number of occurrences of all values in the array; 2. Use the foreach statement to traverse the "$arr2" array to determine whether the number of occurrences of the array value is Greater than 1; 3. Count the number of times greater than 1 to know the number of repeated values in the array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php judgment array How many duplicate values are there
In php, the array_count_values() function can be used to determine how many duplicate values there are in the array
array_count_values() function is used Count the number of occurrences of all values in an array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("A","Cat","Dog","A","Dog",1,2,3,3,2,1); echo "原数组:"; var_dump($arr); echo "数组各值的出现次数:"; $arr2=array_count_values($arr); var_dump($arr2); ?>
It can be seen that the array_count_values() function will return an associative array, the key name of its element is the value of the original array, and the key value is the value that appears in the original array frequency.
In the number of occurrences, any value greater than 1 is a duplicate value. We only need to count the number.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("A","Cat","Dog","A","Dog",1,2,3,3,2,1); $arr2=array_count_values($arr); $count = 0; foreach($arr2 as $value){ if($value>1){ $count ++; } } echo "数组中的重复值有:".$count; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine how many duplicate values there are in an array in php. For more information, please follow other related articles on the PHP Chinese website!