Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple values are all false or all true

How can I check if 20 variables are all true, or if 20 variables are all false?

if possible without using a really long if ...

the variables are actually array elements:

array('a'=> true, 'b'=> true ...)

to make it more clear:

  • if the array has both true and false values return nothing
  • if the array has only true values return true
  • if the array has only false values return false :)
like image 782
sandy Avatar asked Jul 27 '11 19:07

sandy


People also ask

How do you check if all values are false?

sum(data) represents the addition of 1 and 0 with respective values of True(1) and False(0) in a list. In the case of all False sum is 0, and in the case of all True sum is equal to the length of the list. any sum value other than 0 & 1 means not all is False or True.

How do you check if all the elements in the array are true or false?

To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements. Copied!

How do I check if all values in an array are true in PHP?

array('a'=> true, 'b'=> true ...) to make it more clear: if the array has both true and false values return nothing. if the array has only true values return true.

How do you check if a list has all true Python?

The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.


2 Answers

if(count(array_unique($your_array)) === 1)     return current($your_array);  else return; 
like image 75
barfoon Avatar answered Oct 23 '22 17:10

barfoon


You could use in_array

Ex. for all true:

if(in_array(false, $array, true) === false){     return true; } else if(in_array(true, $array, true) === false){     return false; } else{      return 'nothing'; } 
like image 37
afuzzyllama Avatar answered Oct 23 '22 17:10

afuzzyllama