The `count_chars()` function in PHP returns information about the characters used in a string. It can count character occurrences and return the result in different formats.PHP 8.PHP 8.1,PHP 8.2,PHP 8.3 and PHP 8.4.
Syntax
<?php
count_chars(string $string, int $mode = 0): array|string
?>
Parameters:
`$string` - The input string to analyze
`$mode` - Specifies the return format (default is 0):
- Returns an array with byte values as keys and their frequency as values
- Same as 0 but only lists byte values with frequency > 0
- Same as 0 but only lists byte values with frequency = 0
- Returns a string containing all unique characters
- Returns a string containing all unused characters
Example 1: Default mode (0)
<?php
$string = "Hello PHP 8.2!";
$result = count_chars($string, 0);
foreach ($result as $byte => $count) {
if ($count > 0) {
echo "Character '" . chr($byte) . "' appears $count times\n";
}
?>
The `count_chars()` function is useful for text analysis, cryptography, input validation, and other string processing tasks in PHP.