
Wikis & learning
Count repeated labels in an array
A frequency table accumulates a count for each distinct label. Read the current count and add one as each label arrives.
A frequency table accumulates a count for each distinct label. Read the current count and add one as each label arrives.
How it works
Initialize missing keys to zero in the expression. Sorting after counting gives a predictable order to the printed result.
PHP example
<?php
$counts = [];
foreach (['php', 'sqlite', 'php'] as $label) {
$counts[$label] = ($counts[$label] ?? 0) + 1;
}
ksort($counts);
echo json_encode($counts);Expected result
{"php":2,"sqlite":1}
Try a variation
Add sqlite twice. Verify that only its count increases.
Discussion
Sign in to participate.



