Search code examples
phparraysvalidation

How to check if an array contains all false values?


How to check if an array contains all false values?

$arr  = array(false, false, false);
$arr2 = array(true, false, false, 123);

check_false_array($arr);
true
check_false_array($arr2);
false

Not only true/false values are allowed.


Solution

  • Use array_filter() and empty(). array_filter() will remove all false values and if empty() returns true you have all false values.

    function check_false_array(array $array) {
        return empty(array_filter($array, 'strlen'));
    }
    
    var_export(check_false_array(array(false, false, false)));
    echo "\n";
    var_export(check_false_array(array(false, true, false)));
    echo "\n";
    var_export(check_false_array(array(0,0,0)));
    

    Demo

    If you want 0 to be considered false just remove the callback to 'strlen' in array_filter().

    Demo