# Robson » Little Red Book » Letter frequency

## Chapter 7 - Question 13

Process some input text to produce a frequency count for each letter of the alphabet.

### Solution 1

`<?`
`    // if there is no user input text`
`    // or the input text is really long`
`    if (!\$_POST['input_text'] || strlen(\$_POST['input_text']) > 1000)`
`        // just make some up`
`        \$_POST['input_text'] = "Perfection isn't achieved when nothing can be added, but when nothing can be taken away.";`
`    `
`    // save the original text`
`    // remove xhtml tags and slashes`
`    \$_POST['input_text'] = strip_tags(stripslashes(\$_POST['input_text']));`
`    `
`    echo '&quot;' . htmlspecialchars(\$_POST['input_text']) . '&quot;<br /> <br />Has the following letters:<br />';`
`        `
`    // loop through all the letters in the alphabet`
`    for (\$n = ord('a'); \$n <= ord('z'); \$n++)`
`        // count the number of times that letter appears in the input text`
`        // and add it to the array`
`        \$letter[chr(\$n)] = substr_count(strtolower(\$_POST['input_text']), chr(\$n));`
`        `
`    // sort the array by the values in reverse order (highest to lowest)`
`    arsort(\$letter);`
`    `
`    // output aligned for easier reading`
`    echo '<pre>';`
`    // now loop through all the letters in the array`
`    for (\$n = 0; \$n < count(\$letter); \$n++)`
`    {`
`        // grab the key and the value from the letter array`
`        list(\$key, \$val) = each(\$letter);`
`        // if that letter was contained somewhere in the string`
`        if (\$val)`
`            // show the letter frequency`
`            echo \$key . ' - ' .  \$val . '<br />';`
`    }`
`    // return to normal font`
`    echo '</pre>';`
`?>`

Which produces:

"Perfection isn't achieved when nothing can be added, but when nothing can be taken away."

Has the following letters:
`n - 11e - 10a - 7t - 6i - 5h - 5d - 4c - 4o - 3b - 3w - 3g - 2s - 1r - 1v - 1u - 1k - 1f - 1y - 1p - 1`