How to usestr_split() and array_count_values() Functions in PHP
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 w3wiki" ; 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. ...
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