Home >Backend Development >PHP Tutorial >Code in PHP to calculate which character appears most often in a string of unknown length
Function used:
str_split: Split the string into an array. A similar function, the explode() function, splits a string into an array. array_count_values: Used to count the number of occurrences of all values in the array.
arsort: Sort the array in reverse order and maintain the index relationship.
Mainly used for sorting associative arrays where the order of units is important. $str="asdfgfdas323344##$$fdsdfg*$**$*$**$$443563536254fas";//A string of any length
Copy the code The code is as follows:
$arr=str_split($str);
$arr= array_count_values($arr);
arsort($arr);
print_r($arr);
Output:
Copy code The code is as follows:
Array
(
[$] => 7
[3] => 6
[*] => 6
[4] => 5
[f] => 5
[s] => 4
[d] => 4
[5] => 3
[ a] => 3
[6] => 2
[2] => 2
[g] => 2
[#] => 2
)
Second method:
Use Functions:
array_unique: Remove duplicate values in the array. substr_count: Count the number of times a substring appears in a string.
Copy the code The code is as follows:
$str="asdfgfdas323344##$$fdsdfg*$**$*$**$$443563536254fas";//A string of any length
$arr=str_split($str);
$unique =array_unique($arr);
foreach ($unique as $a){
$arr2[$a]=substr_count($str, $a);
}
arsort($arr2);
print_r($arr2);