PHP Count The number of true values ​​in a boolean array

I have an associative array in which I need to count the number of logical true values ​​inside.

The end result is to create an if statement that returns true if there is only one true value in the array. It will need to return false if there is more than one true value in the array, or if there are no true values ​​in the array.

I know that the best way would be to use count and in_array in one form or another. I'm not sure if this will work, just out of my head, but even if that happens, is this the best way?

$array(a->true,b->false,c->true) if (count(in_array(true,$array,true)) == 1) { return true } else { return false } 
+7
source share
5 answers

I would use array_filter.

 $array = array(true, true, false, false); echo count(array_filter($array)); //outputs: 2 

http://codepad.viper-7.com/ntmPVY

Array_filter will remove values ​​that are false-y (value == false). Then just get the bill. If you need to filter based on some special value, for example, if you are looking for a specific value, array_filter accepts an optional second parameter, which is a function that you can define to return true (not filtered) or false (filtered).

+26
source

Since TRUE is passed to 1 and FALSE to 0. You can also use array_sum

 $array = array('a'=>true,'b'=>false,'c'=>true); if(array_sum($array) == 1) { //one and only one true in the array } 

From doc : "FALSE will give 0 (zero), and TRUE will give 1 (one)."

+7
source

Try this approach:

 <?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?> 

Result:

 Array ( [1] => 2 [hello] => 2 [world] => 1 ) 

Documentation

+2
source

like this?

 $trues = 0; foreach((array)$array as $arr) { $trues += ($arr ? 1 : 0); } return ($trues==1); 
0
source

Have you tried using array_count_values to get an array with everything counted? Then check how much is true?

0
source

All Articles