PHP Program to Find Most Frequent Character
count_chars($string, 1) to count characters, then find the max count and its character with array_search(max($counts), $counts) to get the most frequent character in PHP.Examples
How to Think About It
Algorithm
Code
<?php $string = "mississippi"; $counts = count_chars($string, 1); $maxCount = max($counts); $mostFrequentChar = chr(array_search($maxCount, $counts)); echo $mostFrequentChar; ?>
Dry Run
Let's trace the string 'mississippi' through the code to find the most frequent character.
Input string
$string = 'mississippi'
Count characters
$counts = count_chars('mississippi', 1) gives array with counts: m=1, i=4, s=4, p=2
Find max count
$maxCount = max($counts) = 4
Find character with max count
$mostFrequentChar = chr(array_search(4, $counts)) = 'i'
Output result
echo 'i'
| Character | Count |
|---|---|
| m | 1 |
| i | 4 |
| s | 4 |
| p | 2 |
Why This Works
Step 1: Counting characters
The count_chars function counts how many times each character appears in the string and returns an array with character codes as keys and counts as values.
Step 2: Finding the maximum count
Using max() on the counts array finds the highest number of occurrences among all characters.
Step 3: Getting the character
The array_search() finds the character code that matches the max count, and chr() converts that code back to the character.
Alternative Approaches
<?php $string = "hello"; $freq = []; for ($i = 0; $i < strlen($string); $i++) { $char = $string[$i]; if (isset($freq[$char])) { $freq[$char]++; } else { $freq[$char] = 1; } } $maxChar = ''; $maxCount = 0; foreach ($freq as $char => $count) { if ($count > $maxCount) { $maxCount = $count; $maxChar = $char; } } echo $maxChar; ?>
<?php $string = "banana"; $chars = str_split($string); $freq = array_reduce($chars, function($carry, $char) { $carry[$char] = ($carry[$char] ?? 0) + 1; return $carry; }, []); $maxChar = array_keys($freq, max($freq))[0]; echo $maxChar; ?>
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through the string once to count characters, so it runs in linear time relative to string length.
Space Complexity
It uses a fixed-size array for character counts (256 ASCII chars), so space is constant.
Which Approach is Fastest?
Using count_chars is fastest and simplest; manual loops are more flexible but slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| count_chars function | O(n) | O(1) | Quick and efficient for ASCII strings |
| Manual loop with associative array | O(n) | O(n) | Flexible for any character set |
| array_reduce with str_split | O(n) | O(n) | Functional style, less readable for beginners |
count_chars for a quick and efficient way to count character frequencies in PHP.chr() after finding the max count.