PHP array_count_values
array_count_values counts occurrences of integer and string values and uses those values as keys in the result.
A simple example
array_count_values
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
$counts = array_count_values($statuses)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Build a frequency table from order statuses
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
<?php
declare(strict_types=1);
$counts = array_count_values(['new', 'sent', 'new']);
foreach (['new', 'held'] as $status) {
printf("%s=%d\n", $status, $counts[$status] ?? 0);
}
new=2 held=0
An unseen category has no entry. Use the null-coalescing operator to supply zero when printing every expected category.
PHP documentation for array_count_values
Count north-door returns
A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
Count ready print jobs
A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?