0

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)....
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100

3 Answers3

2

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;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Jamie Armour
  • 524
  • 5
  • 10
1
 $successful = count(array_filter($array));
 $failed = count(array_filter($array, function ($v) {return !$v;} ));
Jsowa
  • 9,104
  • 5
  • 56
  • 60
0

You can use array_count_values() and array_map().

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

//array_map converts BOOL values to ints (0 for false, 1 for true)
//array_count_values counts the amount of each value in an array
$counts = array_count_values(
    array_map('intval', $result)
);

$successful = $counts[1];
$failed = $counts[0];
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71