Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

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?

Upvotes: 6

Views: 708

Answers (3)

Wenhuang Lin
Wenhuang Lin

Reputation: 214

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

Upvotes: 0

Hamish
Hamish

Reputation: 23316

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) {
   ...

Upvotes: 7

xdazz
xdazz

Reputation: 160833

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

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

Upvotes: 10

Related Questions