This article mainly introduces the PHP implementation of statistics all characters in the string occurrences of the method, involving the PHP character traversal and statistical operations related operation skills, the need for friends can refer to the next
The example in this article describes how the PHP implementation counts the occurrences of all characters in a string. Share to everyone for your reference, as follows:
First look at the effect:
Algorithm:
Loop the string once (in this case $str
), record the occurrence of the string in an array (as in this example $strRecord
), if already has this record function is not recorded;
In each string, it is compared to the value of the record array (in this case $strRecord[]['key']
), if a value in the record is the same as the string, the number of records is +1 (in this case $strRecord[]['count']
);
Of course, set a variable, the default is False (as in this example $found
), the record each time the comparison, if the record array already has this value, set to True, through this token, the array is not encountered in the array
Implementation code:
<?php//the characters appearing in the statistics string, the number of occurrences echo ' <pre> '; $str = ' AAABBCCQQWWEEDFGHHJFFFFFFFFGGGGGGGGG ';//String example echo $str. ' <br/> '; $strRecord =array ();//To record the occurrences of the character in this array, if there is a record, Then do not log, for ($i =0; $i <strlen ($STR); $i + +) {$found = 0;//default setting is not encountered with foreach ((array) $strRecord as $k + = $v) {if ($str [$i] = = $v [' key ']) {$strRecord [$k] [' count '] + = 1;//has been encountered, Count + 1; $found = 1;//settings have been encountered, Mark continue;//if you have encountered, do not loop the array of records, the following Continuation of the next string comparison}} if (! $found) {$strRecord [] = Array (' key ' = $str [$i], ' count ' =>1);//Record not encountered string}}print_r ($strRecord) ;?