PHP — Counting keys in associative arrays
A PHP associative array can store one counter per label. The null coalescing operator supplies zero for a missing key before the first increment.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
<?php
$counts = ["A" => 2];
echo $counts["A"], PHP_EOL;
2
Count labels without relying on storage order
An associative array maps each color string to a count. The null coalescing operator supplies zero for a missing key, so reading the first occurrence does not trigger a warning.
A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$counts = [];
foreach (['red', 'blue', 'red'] as $color) {
$counts[$color] = ($counts[$color] ?? 0) + 1;
}
foreach (['red', 'blue'] as $color) {
echo $color, ' ', $counts[$color], PHP_EOL;
}
red 2 blue 1
The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.
Try it yourself
Insert another blue before the last red. What changes?
Check your answer
Both keys now have a count of two. The requested display order stays red, then blue.