How to useArrays and str_split() Function in PHP
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 w3wiki" ; countChars( $str ); ?> |
'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. ...
PHP Program to Count the Occurrence of Each Characters
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:
Table of Content
- Using Arrays and str_split() Function
- Using str_split() and array_count_values() Functions
- Using preg_match_all() Function