Program to find how many times a character appears in a string in PHP

In PHP, you can count how many times each character appears in a string by converting the string into an array and iterating through it. This technique is useful for text analysis and character frequency counting.

Example

Here's how to count character occurrences in a string ?

<?php
    $str = "welcome to tutorials point";
    $str = str_replace(" ","", $str);
    $arr = str_split($str);
    
    foreach ($arr as $key => $val) {
        if (!isset($output[$val])) {
            $output[$val] = 1;
        } else {
            $output[$val] += 1;
        }
    }
    
    foreach ($output as $char => $number) {
        echo $char . " " . 'appears ' . $number . " " . 'times' . "<br>";
    }
?>

Output

w appears 1 times
e appears 2 times
l appears 2 times
c appears 1 times
o appears 4 times
m appears 1 times
t appears 4 times
u appears 1 times
r appears 1 times
i appears 2 times
a appears 1 times
s appears 1 times
p appears 1 times
n appears 1 times

How It Works

The code follows these steps ?

  • str_replace() − Removes all spaces from the string
  • str_split() − Converts the string into an array of individual characters
  • foreach loop − Iterates through each character and counts occurrences
  • isset() − Checks if the character has been counted before
  • Display loop − Outputs each character with its frequency count

Conclusion

This method efficiently counts character frequencies by using arrays to track occurrences. The str_split() function makes it easy to process each character individually for counting purposes.

Updated on: 2026-03-15T08:15:28+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements