PHP count_chars() Function – Complete Guide with Examples
What is count_chars() in PHP?
he count_chars()
function in PHP analyzes the frequency of characters in a string. It can:
✔ Count occurrences of each character in a string.
✔ Remove duplicate characters from a string.
✔ Find unique or unused characters.
✔ Convert strings into histograms for text analysis.
📌 Use cases:
- Text processing (word frequency analysis).
- Validating user input (detecting unwanted characters).
- Optimizing data storage (removing unused characters).
Syntax of count_chars()
array|string count_chars(string $string, int $mode = 0)
🔹 Parameters:
$string
→ The input string to analyze.$mode
(optional, default =0
) → Determines how the result is returned.
🔹 Return Value:
- Returns an array (if
$mode = 0, 1, or 2
). - Returns a string (if
$mode = 3 or 4
).
Understanding mode Values in count_chars()
Mode | Description |
---|---|
0 | Returns an array of character frequency (default mode). |
1 | Returns an array of only used characters with their count. |
2 | Returns an array of only unused characters. |
3 | Returns a string containing only unique characters. |
4 | Returns a string containing only duplicate characters. |
Example 1: Count All Characters in a String (mode = 0)
<?php
$string = "hello world";
$result = count_chars($string, 0);
foreach ($result as $char => $count) {
if ($count > 0) {
echo "Character '" . chr($char) . "' appears $count times.\n";
}
}
?>
✅ Output:
Character ' ' appears 1 times. Character 'd' appears 1 times. Character 'e' appears 1 times. Character 'h' appears 1 times. Character 'l' appears 3 times. Character 'o' appears 2 times. Character 'r' appears 1 times. Character 'w' appears 1 times.
📌 How it works?
- The function returns an array where keys represent ASCII values of characters.
chr($char)
converts ASCII values back to characters.
Example 2: Show Only Used Characters (mode = 1)
<?php
$string = "hello world";
$result = count_chars($string, 1);
print_r($result);
?>
✅ Output (Array of used characters):
Array (
[32] => 1 [100] => 1 [101] => 1 [104] => 1 [108] => 3 [111] => 2 [114] => 1 [119] => 1 )
📌 What’s different?
- Only characters that appear in the string are returned (no
0
values). - Keys represent ASCII values, and values represent count of occurrences.
Example 3: Find Unused Characters (mode = 2)
<?php
$string = "hello";
$result = count_chars($string, 2);
print_r($result);
?>
✅ Output (Array of unused characters):
Array (
[0] => 0 [1] => 0 [2] => 0 ...
[97] => 0 [98] => 0 ...
[122] => 0 )
📌 What’s different?
- Returns characters that never appear in
$string
. - Useful for detecting missing characters in an expected set.
Example 4: Get Unique Characters (mode = 3)
<?php
$string = "hello world";
$result = count_chars($string, 3);
echo "Unique characters: $result";
?>
✅ Output:
Unique characters: dehlorw
📌 Why use mode = 3
?
- Removes duplicate characters.
- Returns a string of distinct characters in sorted order.
Example 5: Get Duplicate Characters (mode = 4)
<?php
$string = "hello world";
$result = count_chars($string, 4);
echo "Repeated characters: $result";
?>
✅ Output:
Repeated characters: lo
📌 Why use mode = 4
?
- Returns only characters that appear more than once.
- Useful for finding duplicates in strings.
Best Practices for Using count_chars()
✅ 1. Choose the Right Mode
Use mode 0
for a complete frequency count, but mode 3
or 4
for filtering unique/duplicate characters.
✅ 2. Convert ASCII Values to Characters
When using mode = 0, 1, or 2
, keys are ASCII codes. Use chr($char)
to convert them to readable characters.
✅ 3. Use count_chars()
for Input Validation
Detect unwanted characters in user input, such as invalid symbols in usernames.
✅ 4. Optimize Text Processingcount_chars()
is useful for compression, encryption, and data cleaning.
Alternative Functions to count_chars()
Function | Purpose |
---|---|
strlen() | Counts the total number of characters in a string. |
str_word_count() | Counts words instead of individual characters. |
array_count_values() | Counts values in an array (useful for word frequency). |
mb_strlen() | Multibyte-safe version of strlen() for Unicode support. |
📌 Use count_chars()
when working with character-level analysis, and str_word_count()
for word-based counting.
Summary: When to Use count_chars()
📌 Use count_chars()
when:
✔ Analyzing character frequency in a string.
✔ Finding unique or duplicate characters.
✔ Filtering out unwanted characters.
✔ Optimizing text data (e.g., compression, pattern recognition).
⚠️ Avoid if:
❌ You need word-based analysis → Use str_word_count()
.
❌ You are counting characters in multibyte strings → Use mb_strlen()
.