Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equal variables

Tags:

php

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?

like image 257
The Programmer Avatar asked Jan 21 '26 09:01

The Programmer


1 Answers

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 
}
like image 74
John Conde Avatar answered Jan 23 '26 23:01

John Conde