typestar

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

  1. preg_match_all pulls lowercase words out of the heredoc.
  2. array_count_values builds the frequency table in one call.
  3. arsort ranks it; array_slice keeps the top five.
  4. array_filter with a closure finds the words seen only once.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →