Home > Article > Backend Development > How to detect if there are duplicate values in an array in php
Detection method: 1. Use the "array_unique($arr)" statement to remove duplicate values and obtain the deduplicated array; 2. Use count() to obtain the array lengths of the original array and the deduplicated array respectively; 3. . To determine whether the lengths of two arrays are equal, the syntax is "original array length == deduplicated array length". If they are equal, there are no duplicates in the array.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php detection array Is there a way to duplicate values
Step 1: Use array_unique() to remove duplicate values and return the deduplicated array
array_unique() Function is used to remove duplicate values from an array. If two or more array values are the same, only the first value is retained and the other values are removed; a filtered array is returned.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(3,4,2,3,6,4,7,2,8,9,1); var_dump($arr); $res=array_unique($arr); var_dump($res); ?>
Step 2: Use the count() function to obtain the length of the original array and the deduplicated array
The count() function can Count the number of all elements in the array, that is, get the array length.
$len1=count($arr); $len2=count($res);
Step 3: Determine whether the lengths of the two arrays are equal
$len1==$len2
If the lengths of the two arrays are equal If they are equal, there are no duplicate values in the array
If the lengths of the two arrays are not equal, it means that an element has been removed, that is, there are duplicate values in the array.
Complete code:
<?php header('content-type:text/html;charset=utf-8'); $arr=array(3,4,2,3,6,4,7,2,8,9,1); var_dump($arr); $res=array_unique($arr); var_dump($res); $len1=count($arr); $len2=count($res); if($len1==$len2){ echo "数组里有没有重复值"; }else{ echo "数组里有重复值"; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to detect if there are duplicate values in an array in php. For more information, please follow other related articles on the PHP Chinese website!