Skip to content
Advertisement

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

I’m developing a plugin which does API calls. As a result I’m filling an array with boolean values for success and false.

When my calls are done (multiple calls possible), I want to output a message how many calls were successful and how many failed. This sounds like a simple task, but I have no idea how to do a simple counting.

I’ve found this question here which fits the most but still misses the false counting part:

PHP Count Number of True Values in a Boolean Array

Do you have any idea how I can get this done a simple way?

This is an example array:

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

$successful_calls_count = count($result)....
$failed_calls_count = count($result)....

Advertisement

Answer

You can make the second step pretty easily if you just deduct the successful count from the overall count.

$successful = count(array_filter($array));
$failed = count($array) - $successful;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement