8

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!

tomsseisums
  • 13,168
  • 19
  • 83
  • 145

6 Answers6

31

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

count(array_keys($array, 'yes')) == count($array)
TuomasR
  • 2,296
  • 18
  • 28
  • 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. – tomsseisums Sep 30 '10 at 11:07
  • array_keys is indeed better than array_count_values, because you also can check for array/object elements and enforce strict comparison when desired – user187291 Sep 30 '10 at 12:11
  • don't forget to set the strict parameter when your value is something like 0 --- array_keys($array, 0, true) – Karl Adler Mar 07 '13 at 14:35
9

another possible option

if(count(array_unique($array)) == 1)
Aaron W.
  • 9,254
  • 2
  • 34
  • 45
  • Most elegant and smartest. Of course, `count()` must be `1` with [array_unique()](http://php.net/manual/en/function.array-unique.php) because it "returns a new array without duplicate values." – Avatar Sep 27 '17 at 11:12
2
if($a === array_fill(0, count($a), end($a))) echo "all items equal!";

or better

if(count(array_count_values($a)) == 1)...
user187291
  • 53,363
  • 19
  • 95
  • 127
1
if(count(array_unique($array)) === count($array)) {  
  // all items in $array are the same
}else{
  // at least one item is different
}
Tino
  • 106
  • 6
Dan Wegner
  • 11
  • 1
1

"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
  • 16,130
  • 5
  • 49
  • 43
0

Here's yet another way to go about it, using array_diff with lists

In my case, I had to test against arrays that had all empty strings:

$empty_array = array('','','');  // i know ahead of time that array has three elements
$array_2d = array();
for($array_2d as $arr)
  if(array_diff($arr,$empty_arr)) // 
       do_stuff_with_non_empty_array()  
mrk
  • 4,999
  • 3
  • 27
  • 42