Use an associative array as a counter, one entry for each letter.
What to build
A program that counts how often each letter appears.
Requirements
- Read one line. Ignore capital letters and everything that is not a letter.
- For every letter that appears, in alphabetical order, print
letter: counton its own line.
Input
One line of text.
Output
One line for each letter that appears.
Constraints
The line has at most 200 characters and at least one letter.
Example
Input:
banana
Output:
a: 3
b: 1
n: 2
Why it works
The letter is the key and the count is the value, and ksort puts the keys in alphabetical order.
Examples
Example 1 · Input
banana
Expected output
a: 3 b: 1 n: 2
Example 2 · Input
Hello, World!
Expected output
d: 1 e: 1 h: 1 l: 3 o: 2 r: 1 w: 1
Hints
Hint 1
Make the line lower case, then go through it with str_split.
Hint 2
Count with $counts[$ch] = ($counts[$ch] ?? 0) + 1 and sort with ksort.
Solution
Show one correct solution (try it yourself first)
<?php
$line = strtolower(trim(fgets(STDIN)));
$counts = [];
foreach (str_split($line) as $ch) {
if (ctype_alpha($ch)) {
$counts[$ch] = ($counts[$ch] ?? 0) + 1;
}
}
ksort($counts);
foreach ($counts as $letter => $count) {
echo "$letter: $count\n";
}