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:

<?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:

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!

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top