PHP method to count the number of occurrences of all characters in a string

黄舟
Release: 2023-03-16 17:26:01
Original
1604 people have browsed it

This article mainly introduces PHP's method of counting the number of occurrences of all characters in a string, involving operating techniques related to PHP character traversal and statistical operations. Friends in need can refer to the following

The examples in this article are described PHP implements a method to count the number of occurrences of all characters in a string. Share it with everyone for your reference, the details are as follows:

Let’s take a look at the effect first:

Algorithm:

Loop through the string once ($str in this example) and record the strings that have appeared in an array (such as this In the example $strRecord), if this recording function already exists, it will not be recorded;

is used to compare each string with the value of the record array (in this example $strRecord[]['key']), if a value in the record is the same as this string, record the number of times + 1 ($strRecord[]['count in this example ']);

Of course, set a variable, the default is false (such as $found in this example), record each comparison, if the record array already has this value , set it to true, and use this tag to record the array that has not been encountered into the array

Implementation code:


<?php
//统计字符串中出现的字符,出现次数
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
$str = &#39;aaabbccqqwweedfghhjffffffffggggggggg&#39;;//字符串示例
echo $str.&#39;<br/>&#39;;
$strRecord=array();//把出现过的字符记录在此数组中,如果记录有,则不记录,
for($i=0;$i<strlen($str);$i++){
 $found = 0;//默认设置为没有遇到过
 foreach((array)$strRecord as $k=>$v){
  if($str[$i] == $v[&#39;key&#39;]){
   $strRecord[$k][&#39;count&#39;] += 1;//已经遇到,count + 1;
   $found = 1;//设置已经遇到过的,标记
   continue;//如果已经遇到,不用再循环记录数组了,继续下一个字符串比较
  }
 }
 if(!$found){
  $strRecord[] = array(&#39;key&#39;=>$str[$i],&#39;count&#39;=>1);//记录没有遇到过的字符串
 }
}
print_r($strRecord);
?>
Copy after login

The above is the detailed content of PHP method to count the number of occurrences of all characters in a string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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