Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare more than one values with each other

Tags:

php

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?

like image 639
Ashwini Agarwal Avatar asked Aug 13 '12 07:08

Ashwini Agarwal


2 Answers

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

if (count($arr) !== count(array_unique($arr))) {
  echo 'At-least two variables have same value';
}
like image 67
xdazz Avatar answered Nov 01 '22 08:11

xdazz


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.

E.g.

$values = array(1,2,3,1);
if(max(array_count_values($values)) > 1) {
   ...
like image 40
Hamish Avatar answered Nov 01 '22 09:11

Hamish