How can I count true and false values in my PHP array?


Let’s say the following is our array −

$isMarriedDetails = [
   false,
   true,
   false,
   true,
   true,
   false,
   false,
   true,
   false
];

To count true and false values from an array, at first, count total values and subtract the number of true results. In this way, you will get the number of false values and same for true.

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$isMarriedDetails = [
   false,
   true,
   false,
   true,
   true,
   false,
   false,
   true,
   false
];
$trueResult = count(array_filter($isMarriedDetails));
$falseResult = count($isMarriedDetails) - $trueResult;
echo "Number of false value=",$falseResult,"<br>";
echo "Number of true value=",$trueResult;
?>
</body>
</html>

Output

This will produce the following output

Number of false value=5
Number of true value=4

Updated on: 12-Oct-2020

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements