php-tutorialmade

PHP Script to Count the number of occurrences of a character in a string

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:

Output of the above program will be:

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!

Related Posts

One thought on “PHP Script to Count the number of occurrences of a character in a string

Leave a Reply