PHP count_chars() Function: Description, Parameters, Return Values, and Usage Example
This article explains PHP's count_chars() function, detailing its purpose of counting character occurrences in a string, describing the string and mode parameters, enumerating the five possible return modes, and providing a complete PHP example that demonstrates how to output character frequencies.
count_chars() returns information about the characters used in a string.
Parameters
string : The string to be analyzed.
mode : Determines the format of the returned value (0‑4).
Return values
Depending on mode, count_chars() returns:
0 – an array with all byte values as keys and their occurrence counts as values.
1 – same as 0 but only bytes with a count greater than zero.
2 – same as 0 but only bytes with a count equal to zero.
3 – a string containing all used byte values.
4 – a string containing all unused byte values.
Example
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" . chr($i) . "\" in the string.
";
}
?>The script outputs the number of occurrences for each character, such as:
There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
...Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
