count_chars() counts byte values, not Unicode characters. With mode 1 it returns only byte values that occur at least once; use chr() to display each byte as a character when appropriate.
$counts = count_chars('banana', 1);foreach ($counts as $byte => $count) {
echo chr($byte) . ': ' . $count . PHP_EOL;}$str = "Welcome to plus2net PHP section";$position = count_chars($str,3);print_r($position);
Output
2HPWceilmnopstu
Using count_chars() function we can get many information about an input string. Here is the syntax
count_chars(string $string, int $mode = 0): array|string
$string : Main string to count chars0: an array of all 256 byte values and their frequencies (including zero counts)
1: an array containing only byte values present in the string
2: an array containing only byte values absent from the string
3: a string containing the distinct byte values present, sorted in byte order
4: a string containing the distinct byte values absent, sorted in byte order
$str = "Welcome to plus2net PHP section";$position = count_chars($str,2);print_r($position);
Mode 2 returns an array containing only byte values absent from the string. By using print_r function we have displayed all keys with values of the array. Only absent byte values appear as keys, each with a zero count. Mode 0 includes all 256 byte values, both present and absent.
With different mode values ( 0 to 4) we will get returns like this
We will try some examples here
$str = " Welcome to plus2net PHP section";$position = count_chars($str,1);print_r($position);
The output is here
Array ( [32] => 5 [50] => 1 [72] => 1 [80] => 2 [87] => 1 [99] => 2 [101] => 4 [105] => 1 [108] => 2
[109] => 1 [110] => 2 [111] => 3 [112] => 1 [115] => 2 [116] => 3 [117] => 1 )
Let us change the mode value to 3, this is the only line to be changed.
$position = count_chars($str,3);
The output is here
2HPWceilmnopstu
So you can see the above chars only we have used in our main string. $str = " ron@domain.com, kris@example.com, benoy@testing.com";$position = count_chars($str,1);echo $position[64]; // output is 3
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.