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!
Not a single function, but the same could be achieved easily(?) with:
count(array_keys($array, 'yes')) == count($array)
another possible option
if(count(array_unique($array)) == 1)
if($a === array_fill(0, count($a), end($a))) echo "all items equal!";
or better
if(count(array_count_values($a)) == 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;
}
if(count(array_unique($array)) === count($array)) {
// all items in $array are the same
}else{
// at least one item is different
}
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()
精彩评论