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.
