How to Use count_chars() Function in PHP 8.2 With Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `count_chars()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `count_chars()` function is used to count the number of occurrences of each byte-value (0 to 255) in a string. This function returns either an array or a string depending on the value of the second parameter passed to it. Here’s how you can use `count_chars()` function in PHP 8.2 with an example:


// Example string
$string = "hello world";

// Using count_chars with mode 0 (default), returns an array with the ASCII values as keys and their frequencies as values
$resultArray = count_chars($string, 0);
echo "Byte values and their frequencies in the string:\n";
foreach ($resultArray as $byteValue => $frequency) {
echo "Byte value: $byteValue, Frequency: $frequency\n";

// Using count_chars with mode 1, returns a string containing all the distinct characters used in the string
$resultString = count_chars($string, 1);
echo "\nDistinct characters used in the string: $resultString\n";



Byte values and their frequencies in the string:
Byte value: 32, Frequency: 1
Byte value: 100, Frequency: 1
Byte value: 101, Frequency: 1
Byte value: 104, Frequency: 1
Byte value: 108, Frequency: 3
Byte value: 111, Frequency: 2
Byte value: 114, Frequency: 1
Byte value: 119, Frequency: 1

Distinct characters used in the string: dehlorw

In this example, the first call to `count_chars()` with mode 0 returns an array where each key represents a byte value (ASCII value) present in the string, and the corresponding value represents the frequency of that byte value in the string.