PHP Count Number of True Values in a Boolean Array PHP Count Number of True Values in a Boolean Array arrays arrays

PHP Count Number of True Values in a Boolean Array


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


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)."


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