Do you want to know the simplest way to count the number of occurrences of a character in a string using PHP?
Here is the answer for that. PHP has a default function to do that count_chars()
And here is the sample program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php //program to find the number of occurrences of a character in a string //tutorialsmade.com $string = "Hello World"; //first replace the space between words $string = str_replace(' ', '', $string); //now use the default function count_chars //to get the ascii value and the number of occurrences //of each letter $str_array = count_chars($string, 1); //loop through the array and print the value foreach ($str_array as $ascii => $occurences) { echo chr($ascii) . '- occurs ' . $occurences . ' time(s)<br />'; } ?> |
Output of the above program will be:
1 2 3 4 5 6 7 |
H- occurs 1 time(s) W- occurs 1 time(s) d- occurs 1 time(s) e- occurs 1 time(s) l- occurs 3 time(s) o- occurs 2 time(s) r- occurs 1 time(s) |
count_chars() returns the result as an array, where the ‘key’ contains the ASCII value of a character and the ‘value’ contains the number of occurrences of each character.
To get the character of the ASCII value, used char() in the above snippet, which is again a default PHP function.
And i removing the spaces between the words to avoid counting the space values. If you want to count even the number of spaces in a string, just remove the line no. 9
Hope it helped you. Enjoy the day!
Really Nice place to learn php and that too in simplest way..