If any of these variables are equal to each other

Is there a quick way of doing this in php?

I have 4 variables, and I want to see if any of them are equal. It’s easy to do, but eventually I’ll increase it to 8 or 12, which will get pretty tedious.

I COULD do some magic with arrays and foreach, but is there a way to do it without arrays?

Anyways, I’m going to work on my array trick and post it here when it’s done.

Thanks guys

If this is going to scale I think arrays is the way to go. It gets messy real quick, eg. with only $a $b $c $d $e

if $a == $b or $a == $c or $a == $d or $a == $e or $b == $c or $b == $d or $b == $e or $c == $d or $c == $e or $d == $e

and will grow exponentially the more you compare. If you only want to know if any are equal you could do

$all_vars = array($a, $b, $c, $d, $e);
$checked = array_unique($all_vars);
if (count($all_vars) != count($checked)){
// do something

Pretty sure arrays are your best bet, since PHP has so many built-in functions for handling them. You didn’t say what the outcome of the operation would be. If you need to return duplicate values, check this comment in the PHP manual. If you simply need to return true or false if there’s a match…

$variables = array(
    'var1' => $var1,
    'var2' => $var2,
    'var3' => $var3,
    'var4' => $var4,

//Assert if a duplicate exists
function arrayHasDuplicateValues($variables)
    if(count($variables) > count(array_unique($variables))
        return true;
    return false;


if ($a == $b or $a == $c or $a == $d or $a == $e){

//using in_array()
if(in_array($a, array($b,$c,$d,$e)){


similar goes for rest.
but i don’t think this is a best way to go.

It sounds like this will indeed get very complicated. Is it possible to re-write the code so as not to depend on so many variables?

What exactly are the variables for, and what values can you expect them to have? Do you need them ALL to match, or just any two to match?

I think you may need to re-think what you are trying to achieve, otherwise you will just have to deal with the ugly code :stuck_out_tongue:

The requirement was to see if ANY of them are equal, not all of them, unfortunately. Your code wont work if $c & $d are equal for example.