简体   繁体   中英

Compare more than one values with each other

I have about 20 different variables and i want to compare this variables with each other to check weather they are equal or not.

Example

$var1 = 1;
$var2 = 2;
$var3 = 1;
$var4 = 8;
.
.
.
$var10 = 2;

Now i want to check...

if($var1 == $var2 || $var1 == $var3 || $var1 == $var4 || ......... || $var2 == $var3 || $var2 == $var4 || ............. || $var8 = $var9 || $var8 == $var10 ||...)
{
    echo 'At-least two variables have same value';
}

I am finding for an easy to do this. Any Suggestions?

$arr = array($var1, $var2, ... , $var10);

if (count($arr) !== count(array_unique($arr))) {
  echo 'At-least two variables have same value';
}

If you want to find out if any of the variables are duplicates, put them in an array and use the array_count_values :

array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

If you have any values greater than 1 in the result, there is a match.

Eg

$values = array(1,2,3,1);
if(max(array_count_values($values)) > 1) {
   ...

firstly,save them to an array,and everything becomes easy

$list=array("1"=>$var1,"2"=>$var2,......,"10"=>$var10);
$list2=array_unique($list);
if(count($list2) != count($list))
    echo 'At-least two variables have same value';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM