Home  >  Article  >  Backend Development  >  How to detect if there are duplicate values ​​in an array in php

How to detect if there are duplicate values ​​in an array in php

青灯夜游
青灯夜游Original
2022-05-31 19:22:184409browse

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.

How to detect if there are duplicate values ​​in an array in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(3,4,2,3,6,4,7,2,8,9,1);
var_dump($arr);
$res=array_unique($arr);
var_dump($res);
?>

How to detect if there are duplicate values ​​in an array in php

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);

How to detect if there are duplicate values ​​in an array in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$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 "数组里有重复值";
}
?>

How to detect if there are duplicate values ​​in an array in php

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!

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