Home > Backend Development > PHP Tutorial > Code in PHP to calculate which character appears most often in a string of unknown length

Code in PHP to calculate which character appears most often in a string of unknown length

高洛峰
Release: 2023-03-02 16:56:01
Original
923 people have browsed it

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);

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template