Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sometimes, we need to know how many of each character is in a string. This PHP code does just that.
function getLetterCount($input) {
$letters = array();
//make lowercase to simplify counting
$temp = strtolower(trim($input));
//get length of string
$templen = strlen($temp);
//get each character in string
for($i = 0; $i < $templen; $i++) {
$char = substr($temp, $i, 1);
//if it's a letter, increment its counter in array
if(eregi('[a-z]', $char)) {
$letters[$char] += 1;
//sort array by key name
//return array
return $letters;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
Count Letters In A String With PHP
Copyright 2007 Doug Vanderweide, dba Rescue-ME
Distributed under the Creative Commons Attribution / Share-Alike 2.5 License
Any distribution or derivative work based on this script must include the
original source code from this work, and must retain this copyright
notice block intact.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Count Letters In A String With PHP</title>
<link href="../demo.css" rel="stylesheet" type="text/css" />
<h1>Count Letters In A String With PHP</h1>
if(isset($_POST['submit'])) {
$countstring = substr($_POST['mystring'], 0, 255);
$output = getLetterCount($countstring);
echo "<h3>The input string was:</h3>\n";
echo $countstring;
echo "<h3>Letter count displayed using foreach:</h3>\n";
foreach($output as $key => $value) {
echo "$key: $value<br />";
//output array to screen
echo "<h3>Letter count displayed using print_r:</h3>\n";
$mystring = $_POST['mystring'];
else {
$mystring = "The quick brown fox jumps over the lazy dog.";
<form id="form1" name="form1" method="post" action="">
<label for="textfield">Enter the string:</label>
<input name="mystring" type="text" id="mystring" value="<? echo $mystring; ?>" size="50" maxlength="255" />
<input name="submit" type="submit" id="submit" value="Count Letters" />
<p><a href="" rel="bookmark" title="Permanent Link to Counting Letters In A String With PHP">Counting Letters In A String With PHP</a></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.