word_freq.php in PHP
A word-frequency report over an inline passage, built from array functions.
<?php
// word_freq: count word occurrences in an inline passage
$text = <<<TEXT
The quick brown fox jumps over the lazy dog.
The dog barks; the fox runs. Quick thinking, that fox.
TEXT;
preg_match_all('/[a-z]+/', strtolower($text), $matches);
$words = $matches[0];
$freq = array_count_values($words);
arsort($freq);
echo "words total: ", count($words), "\n";
echo "words unique: ", count($freq), "\n";
echo "top 5:\n";
foreach (array_slice($freq, 0, 5, true) as $word => $count) {
printf(" %-8s %d\n", $word, $count);
}
$once = array_keys(array_filter($freq, fn ($n) => $n === 1));
sort($once);
echo "seen once: ", implode(", ", $once), "\n";
How it works
preg_match_allpulls lowercase words out of the heredoc.array_count_valuesbuilds the frequency table in one call.arsortranks it;array_slicekeeps the top five.array_filterwith a closure finds the words seen only once.
Keywords and builtins used here
array_count_valuesarray_filterarray_keysarray_slicearsortascountechoforeachimplodepreg_match_allprintfsortstrtolowertrue
The run, in numbers
- Lines
- 25
- Characters to type
- 649
- Tokens
- 136
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 96 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.