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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP count_chars() Function: Description, Parameters, Return Values, and Usage Example

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.
...
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPStringfunctioncount_chars
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.