tomsseisums
tomsseisums

Reputation: 13367

Checking all array values at once

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!

Upvotes: 8

Views: 19200

Answers (6)

Dan Wegner
Dan Wegner

Reputation: 11

if(count(array_unique($array)) === count($array)) {  
  // all items in $array are the same
}else{
  // at least one item is different
}

Upvotes: 1

mrk
mrk

Reputation: 5117

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()  

Upvotes: 0

grahamparks
grahamparks

Reputation: 16296

"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;
}

Upvotes: 1

Aaron W.
Aaron W.

Reputation: 9299

another possible option

if(count(array_unique($array)) == 1)

Upvotes: 9

user187291
user187291

Reputation: 53940

if($a === array_fill(0, count($a), end($a))) echo "all items equal!";

or better

if(count(array_count_values($a)) == 1)...

Upvotes: 2

TuomasR
TuomasR

Reputation: 2316

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

count(array_keys($array, 'yes')) == count($array)

Upvotes: 31

Related Questions