Home > Article > Backend Development > How to count the number of different characters in a string in php
Statistical method: 1. Use the "str_split(string)" statement to split the string and convert it into a character array; 2. Use the "sizeof(array_count_values(character array))" statement to count the individual numbers of different characters Just count.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php statistical string The number of different characters in
In PHP, you can use the array function to count the number of different characters in a string.
First use str_split() to convert the string into a character array
Use array_count_values() to count the number of occurrences of all values in the character array. An associative array will be returned, the key name of its element is the value of the original array, and the key value is the number of times the value appears in the original array.
The key names of the associative array are different characters in the string
Use sizeof() to count the number of elements in the associative array.
Implementation code:
<?php header("Content-type:text/html;charset=utf-8"); $str = "1234jhv4321vs;s"; $arr = str_split($str); //字符串分隔到数组中 $arr=array_count_values($arr); var_dump($arr); $gs = sizeof($arr); echo "字符串中有 ".$gs." 个不同字符"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to count the number of different characters in a string in php. For more information, please follow other related articles on the PHP Chinese website!