Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I count true and false values in my PHP array?
In PHP, you can count true and false values in an array using array_filter() combined with count(). The array_filter() function removes falsy values by default, making it perfect for counting true values.
Syntax
$trueCount = count(array_filter($array)); $falseCount = count($array) - $trueCount;
Example
Let's count true and false values from a boolean array −
<?php
$isMarriedDetails = [
false,
true,
false,
true,
true,
false,
false,
true,
false
];
$trueResult = count(array_filter($isMarriedDetails));
$falseResult = count($isMarriedDetails) - $trueResult;
echo "Number of false values: " . $falseResult . "
";
echo "Number of true values: " . $trueResult;
?>
Number of false values: 5 Number of true values: 4
How It Works
The array_filter() function removes all falsy values (false, 0, null, empty string) from the array. When we count the filtered array, we get the number of true values. Subtracting this from the total count gives us the false values.
Alternative Method
You can also use array_count_values() to get counts of each unique value −
<?php $boolArray = [true, false, true, false, false, true]; $counts = array_count_values($boolArray); echo "True values: " . ($counts[1] ?? 0) . "
"; echo "False values: " . ($counts[0] ?? 0); ?>
True values: 3 False values: 3
Conclusion
Use array_filter() with count() for a simple approach, or array_count_values() when you need counts of all unique values in the array.
