105 of 410 menu

The count_chars Function

The count_chars function counts how many times different characters occur in a string.

The first parameter of the function is the string, and the second optional parameter is a modifier that changes the result of the function.

Syntax

count_chars(string $string, int $mode = 0): array|string

Modifier Values

Depending on the value of the parameter, the function returns the following:

  • Value 0 - an array whose keys are ASCII codes, and the values are the number of occurrences of the corresponding character.
  • Value 1 - the same as for 0, but information about characters with zero occurrences is not included in the array.
  • Value 2 - the same as for 0, but the array includes information only about characters with zero occurrences.
  • Value 3 - a string consisting of characters that appear in the original string at least once.
  • Value 4 - a string consisting of characters that do not appear in the original string.

By default, the function behaves as if the second parameter is set to 0.

Example

Let's count the number of characters in a string by setting the modifier to value 1:

<?php $str = 'aaabbc'; $res = count_chars($str, 1); var_dump($res); ?>

As a result, the function will return codes of all characters from 0 to 255, and among these codes will be the codes of our characters from the string:

[ 0 => 0, 1 => 1, ... 97 => 3, // 97 is the code of the character 'a' 98 => 2, // 98 is the code of the character 'b' 99 => 1, // 99 is the code of the character 'c' ... 255 => 0, ]

Example

Let's count the number of characters in a string by setting the modifier to value 1:

<?php $str = 'aaabbc'; $res = count_chars($str, 1); var_dump($res); ?>

As a result, the function will return only the codes of the found characters and the number of these characters:

[ 97 => 3, // 97 is the code of the character 'a' 98 => 2, // 98 is the code of the character 'b' 99 => 1, // 99 is the code of the character 'c' ]

See Also

  • the substr_count function,
    which counts the number of substrings
  • the count_chars function,
    which counts the number of characters
  • the str_word_count function,
    which counts the number of words
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline