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

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

WBOY
Release: 2016-07-21 15:17:03
Original
1018 people have browsed it

Functions 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: Reverse sort the array and maintain the index relationship.
Mainly used for sorting associative arrays where the order of units is important. $str="asdfgfdas323344##$$fdsdfg*$**$*$**$$443563536254fas";//Any length string

Copy 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:
Function used:
array_unique: delete duplicate values ​​in the array. substr_count: Count the number of times a substring appears in a string.
Copy code The code is as follows:

$str="asdfgfdas323344##$$fdsdfg*$**$*$* *$$443563536254fas";//Any 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);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325755.htmlTechArticleFunction 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...
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