tags:

views:

41

answers:

4

Is there a simple way to check if all values in array are equal to each other?

In this case, it would return false:

$array[0] = 'yes';
$array[1] = 'yes';
$array[2] = 'no';

And in this case, true:

$array[0] = 'yes';
$array[1] = 'yes';
$array[2] = 'yes';

So, yeah, is there a function/method to check all array values at once?

Thanks in advance!

+4  A: 

Not a single function, but the same could be achieved easily(?) with:

count(array_keys($array, 'yes')) == count($array)
TuomasR
From all of provided solutions this was the easiest to understand, provides most functionality and is really simple! +1, accepted. Huge bonus for that `yes` check.
Tom
array_keys is indeed better than array_count_values, because you also can check for array/object elements and enforce strict comparison when desired
stereofrog
+1  A: 
if($a === array_fill(0, count($a), end($a))) echo "all items equal!";

or better

if(count(array_count_values($a)) == 1)...
stereofrog
+2  A: 

another possible option

if(count(array_unique($array)) == 1)
Aaron W.
A: 

"All values the same" is equivalent to "all values equal to the first element", so I'd do something like this:

function array_same($array) {
  if (count($array)==0) return true;

  $firstvalue=$array[0];
  for($i=1; $i<count($array); $i++) {
      if ($array[$i]!=$firstvalue) return false;
  }
  return true;
}
grahamparks