The code in php that calculates which character appears the most in a string of unknown length
- 2020-05-19 04:19:27
- OfStack
Functions used:
str_split: splits the string into an array. A similar function, explode(), splits a string into an array. array_count_values: used to count the number of occurrences of all the values in an array.
arsort: reverse sort the array and keep the index.
It is primarily used to sort associative arrays where the order of the cells is important. $str = "asdfgfdas323344 # # $$fdsdfg \ * $$$$$* * * * * 443563536254 fas"; // any length string
Output:
Method 2:
Functions used:
array_unique: removes duplicate values from an array. substr_count: counts the number of times a substring appears in a string.
str_split: splits the string into an array. A similar function, explode(), splits a string into an array. array_count_values: used to count the number of occurrences of all the values in an array.
arsort: reverse sort the array and keep the index.
It is primarily used to sort associative arrays where the order of the cells is important. $str = "asdfgfdas323344 # # $$fdsdfg \ * $$$$$* * * * * 443563536254 fas"; // any length string
$arr=str_split($str);
$arr=array_count_values($arr);
arsort($arr);
print_r($arr);
Output:
Array
(
[$] => 7
[3] => 6
[*] => 6
[4] => 5
[f] => 5
[s] => 4
[d] => 4
[5] => 3
[a] => 3
[6] => 2
[2] => 2
[g] => 2
[#] => 2
)
Method 2:
Functions used:
array_unique: removes duplicate values from an array. substr_count: counts the number of times a substring appears in a string.
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";// Arbitrary length string
$arr=str_split($str);
$unique=array_unique($arr);
foreach ($unique as $a){
$arr2[$a]=substr_count($str, $a);
}
arsort($arr2);
print_r($arr2);