Open In App

PHP Program to Count the Occurrence of Each Characters

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, the task is to count the occurrences of each character using PHP. This article explores various approaches to achieve this task using PHP, These are:

Approach 1: Using Arrays and str_split() Function

This approach involves splitting the input string into an array of individual characters using str_split() function. The array_count_values() function is then applied to obtain the count of each unique character in the array. Finally, a loop iterates through the counts and prints the occurrences for each character.

PHP




<?php
  
function countChars($str) {
    $chars = str_split($str);
    $count = array_count_values($chars);
  
    foreach ($count as $char => $occurrences) {
        echo "'$char' occurs $occurrences times.\n";
    }
}
  
// Driver code
$str = "Welcome GeeksforGeeks";
  
countChars($str);
  
?>


Output

'W' occurs 1 times.
'e' occurs 6 times.
'l' occurs 1 times.
'c' occurs 1 times.
'o' occurs 2 times.
'm' occurs 1 times.
' ' occurs 1 times.
'G' occurs 2 times.
'k' occurs 2 times.
's' occurs 2 times.
...

Approach 2: Using str_split() and array_count_values() Functions

This approach combines str_split() and array_count_values() function directly within the function. It streamlines the process by avoiding the intermediate variable for the characters array.

PHP




<?php
  
function countChars($str) {
    $count = array_count_values(str_split($str));
  
    foreach ($count as $char => $occurrences) {
        echo "'$char' occurs $occurrences times.\n";
    }
}
  
// Driver code
$str = "Welcome GeeksforGeeks";
  
countChars($str);
  
?>


Output

'W' occurs 1 times.
'e' occurs 6 times.
'l' occurs 1 times.
'c' occurs 1 times.
'o' occurs 2 times.
'm' occurs 1 times.
' ' occurs 1 times.
'G' occurs 2 times.
'k' occurs 2 times.
's' occurs 2 times.
...

Approach 3: Using preg_match_all() Function

This approach leverages regular expressions through preg_match_all() to match all characters in the Unicode string (/./u). The resulting matches are then processed using array_count_values() to get the count of each character, and a loop prints the occurrences.

PHP




<?php
  
function countChars($str) {
    preg_match_all('/./u', $str, $matches);
    $count = array_count_values($matches[0]);
  
    foreach ($count as $char => $occurrences) {
        echo "'$char' occurs $occurrences times.\n";
    }
}
  
// Driver code
$str = "Welcome GeeksforGeeks";
  
countChars($str);
  
?>


Output

'W' occurs 1 times.
'e' occurs 6 times.
'l' occurs 1 times.
'c' occurs 1 times.
'o' occurs 2 times.
'm' occurs 1 times.
' ' occurs 1 times.
'G' occurs 2 times.
'k' occurs 2 times.
's' occurs 2 times.
...



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads