PHP 8.5 count_chars() Function With Example

The count_chars() function counts the frequency of every possible byte value (0-255) in a string. It returns either an array or a string, depending on the mode you specify.

The Modes

  • 0: Array with all byte values as keys and their counts.
  • 1: Array with only byte values that appear in the string.
  • 2: Array with byte values that do not appear.
  • 3: String containing all unique characters used.
  • 4: String containing characters not used.

Example (Mode 1)

This example finds how many times each character appears in a string.

<?php
$str = "Hello";

// Mode 1: Only returns characters that actually exist
foreach (count_chars($str, 1) as $byte => $count) {
   echo "Character " . chr($byte) . " appears $count time(s). ";
}
?>

Output:

Character H appears 1 time(s).
Character e appears 1 time(s).
Character l appears 2 time(s).
Character o appears 1 time(s).

Note: This function counts single bytes, not UTF-8 characters. For multi-byte text (like Hindi), use mb_str_split() or similar functions instead.

6 Views