2

I wondered if there is any way to check if any of a large amount of variables are equal. If I only have a few variables I can just do this:

if ($a == $b || $a == $c || $b == $c)

However, if I have 20 variables it will take some time to write all combinations. Is there another method?

0

1 Answer 1

13
if (count(array_unique(array($a, $b, $c), SORT_REGULAR)) === 1) {
    // all equal
}

All this code does is place the variables in an array and eliminates duplicates. If they are all equal the result of array_unique() should be an array with one value.

If you want to make sure all of them are different it's not much different. Just check to see if the filtered array is the same size as the original array:

$array = array($a, $b, $c);
if (count(array_unique($array, SORT_REGULAR)) === count($array)) {
    // all not equal 
}
Sign up to request clarification or add additional context in comments.

6 Comments

Probably a good idea to use the SORT_REGULAR flag with array_unique.
I think that's a good idea, too. Added it to my answer. Thank you for the feedback.
Sorry for bad explanation, but what I need is to check if no variables are equal, not if all are equal. Do you have any idea how to do that?
awesome answer ruined by poorly asked questions.
Now where's that +10 upvote on comments button when you need one? @Dagon --- +1 ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.