Home  >  Article  >  Backend Development  >  How to count the number of different characters in a string in php

How to count the number of different characters in a string in php

青灯夜游
青灯夜游Original
2022-02-17 19:18:192537browse

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.

How to count the number of different characters in a string in php

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." 个不同字符";
?>

How to count the number of different characters in a string in php

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!

Statement:
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
Previous article:What does die mean in phpNext article:What does die mean in php