Counting Letters In A String With PHP

Recently asked on Yahoo! Answers:

Using PHP to show how many letters in a word?

Is there a way to find out how many of a certain letter are in variables with php?
e.g. $5 = ‘dinosaurs’;

So it somehow echos how many of each letter there is?
e.g.
1-d
1-i
1-n
1-o
2-s
1-a
1-u
1-r

There is a built-in PHP function called count_chars(). However, it will count everything — spaces, numbers, punctuation, etc. It also builds in the ability to select all characters, only those characters that exist in the string more than once and only those characters that don’t appear in a string. It doesn’t really work the way the questioner asked, so we’ll proceed with our own function.

This is easily done by making a function that will store, in an associative array, all the letters present in the string, plus the count for each.

The function we will name getLetterCount(); it will accept a string as an argument. It will return an associative array; the key will be the letter; the value will be the number of times the letter appears in our string.

The function will not count non-letter characters; that is, numbers, spaces, newlines, punctuation, etc. will be ignored. We could certainly count those, and I’ll discuss that mod at the appropriate moment.

We begin by declaring the function and creating the array this function will return. We’ll also cast the string to lowercase, so we can make a case-insensitive count; and we’ll trim whitespace from the start and end of the string, since it’s meaningless to us. (If we were going to count spaces, too, we wouldn’t want to trim this string).

function getLetterCount($input) {
	$letters = array();
 
	//make lowercase to simplify counting
	$temp = strtolower(trim($input));
 
	//get length of string
	$templen = strlen($temp);

We next use a for loop to get one character from a time from the input string. We examine each character and check to see if it is a letter (a-z) via eregi; if we have a letter, we simply increment the corresponding array key by 1.

The nice thing about PHP is that because it supports dynamic arrays, we don’t need to have a letter key in the array before we try to increment it; if a letter key doesn’t exist, PHP will create it for us and assign it a value of 1.

For example, if we run the word “Ava” through this function:

  • On the first pass of the for loop, PHP will create an ‘a’ key and set its value to 1.
  • On the second pass, PHP will create a ‘v’ key and set its value to 1.
  • On the third and final pass, PHP will increment the ‘a’ key by 1, making its value 2.
	//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;
		}
	}

The regular expression for the full range of lowercase letters is [a-z]. If you want to be able to seach for additional characters, here are some alternative regexs; you’d simply replace the first argument of eregi, above, with one of these:

  • Any letter or number: ‘\w’
  • Any letter, number or space: ‘\w\s’

Otherwise, simply use count_chars(), and all characters of all types will be counted.

To finish, we’ll sort the array by its key names, then return the array:

	//sort array by key name
	ksort($letters);
 
	//return array
	return $letters;
}

That’s it!

To display our results, we can use print_r(), which will echo out the array keys and values; or, if we want more control over how we manipulate the output, we can use foreach().

I have a demonstration of this code here:

http://www.dougv.com/demo/count_letters_in_string_php/

You can download this code from here:

Counting Letters In A String With PHP Demo Code

As always, I distribute code under the most recent version of the Creative Commons Attribution / Share-Alike License.

Share This »
  • Digg
  • Yahoo! Buzz
  • Technorati
  • del.icio.us
  • Propeller
  • StumbleUpon
  • Reddit
  • Mixx
  • Twitter / Twit This
  • Pownce
  • Fark
  • Slashdot
  • NewsVine
  • BlinkList
  • Netvouz
  • Furl
  • Mister Wong
  • DZone
  • Ma.gnolia
  • Simpy
  • blogmarks
  • Blue Dot
  • Spurl
  • Sphinn
  • DotNetKicks
  • MySpace
  • Facebook
  • LinkedIn
  • Google Bookmarks
  • Yahoo! MyWeb
  • Windows Live Favorites

One Comment

  1. Andrew:

    Amazing, thanks very much.

Leave a comment