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

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

Modifier Values

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

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<?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:

php[
  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<?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:

php[
  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