PHP Count Number of True Values in a Boolean Array

我只是一个虾纸丫 提交于 2019-12-21 03:42:59

问题


I have an associative array in which I need to count the number of boolean true values within.

The end result is to create an if statement in which would return true when only one true value exists within the array. It would need to return false if there are more then one true values within the array, or if there are no true values within the array.

I know the best route would be to use count and in_array in some form. I'm not sure this would work, just off the top of my head but even if it does, 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
}

回答1:


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 a count. If you need to filter based on some special value, like if you are looking for a specific value, array_filter accepts an optional second parameter that is a function you can define to return whether a value is true (not filtered) or false (filtered out).




回答2:


Since TRUE is casted to 1 and FALSE is casted 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 the doc : "FALSE will yield 0 (zero), and TRUE will yield 1 (one)."




回答3:


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




回答4:


like this?

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



回答5:


Have you tried using array_count_values to get an array with everything counted? Then check how many true's there are?



来源:https://stackoverflow.com/questions/16428635/php-count-number-of-true-values-in-a-boolean-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!