Funnily enough, today I found this wee bit of code that has been sitting on my drive for no earthly reason that I can still discern:
<?php
function sort_words($a,$b)
{
// Sorting in descending order by frequency (0th element);
// tiebreaks decided lexicographically (1st element)
if($t = $b[0]-$a[0]) return $t;
return strcmp($b[1],$a[1]);
}
// Read in a file from stdin, convert it to lower case, break it into
// "words" of consecutive letters, and count the words. Don't include
// the two null words that "appear" at the very ends of the file.
$words = array_count_values(
preg_split('/[^a-z]+/',
strtolower(file_get_contents('php://stdin')),
-1, PREG_SPLIT_NO_EMPTY));
// Get the key and value for each element of the $words array,
// make an array of the pair, and store it as an element.
// Annoyingly necessary, since the inbuilt sort functions neither
// accept key-value pairs directly, nor - using quicksort as they do -
// are they stable. (If they were stable, one could have sorted the
// list as per spec in place by writing
// arsort($words);
// krsort($words);
// instead of the custom comparison function and the following two lines.)
$words = array_map(null, array_values($words), array_keys($words));
usort($words,'sort_words');
foreach($words as $pair)
{
printf("%7d %s\n", $pair[0], $pair[1]);
}
?>