The count_chars() function analyzes a string at the byte level, counting how often each value from 0 to 255 appears. With five modes, it can return full frequency tables, compact maps, or strings of unique characters—ideal for validation, puzzles, and text analysis.
01
Byte Frequencies
Count 0–255 bytes.
02
Five Modes
Array or string output.
03
Mode 1 Best
Compact frequency map.
04
Case Sensitive
A ≠ a in counts.
05
Unique Chars
Mode 3 string output.
06
Anagram Checks
Compare frequency maps.
Fundamentals
Definition and Usage
In PHP, count_chars() scans every byte in a string and records how many times each byte value occurs. Array keys are numeric ASCII/byte values (use chr() to convert them to characters). Mode 1 is the most practical—it returns only bytes that actually appear, keeping the result small and readable.
💡
Beginner Tip
count_chars() works on bytes, not Unicode characters. For ASCII text like passwords or English words, mode 1 gives you a perfect letter-frequency map. For UTF-8 text with accents or non-Latin scripts, use mb_strlen() and mb_substr() instead.
Foundation
📝 Syntax
The count_chars() function accepts a string and an optional mode:
PHP
array|string count_chars(string $string, int $mode = 0)
Parameters
$string — the string to analyze.
$mode (optional, default 0) — controls the return format. See the mode table below.
Return Value by Mode
Mode 0 — array with all 256 byte values (0–255) as keys and their frequencies as values.
Mode 1 — same as mode 0, but only bytes with a frequency greater than zero are included. Most commonly used.
Mode 2 — same as mode 0, but only bytes with a frequency equal to zero (bytes not present in the string).
Mode 3 — a string containing all unique characters used, ordered by ascending byte value.
Mode 4 — a string containing all byte characters not used in the string (can be very long).
Cheat Sheet
⚡ Quick Reference
Mode 1 (best)
count_chars($s, 1)
Compact frequency map
Read one char
$c[ord('a')] ?? 0
Count of letter a
Unique chars
count_chars($s, 3)
String of uniques
Unique count
count(count_chars($s,1))
Number of distinct bytes
Hands-On
Examples Gallery
Run these examples in PHP 7+. Each demonstrates a common pattern beginners encounter with count_chars().
📚 Getting Started
Build a readable character frequency map with mode 1.
Example 1 — Character Frequency Map (Mode 1)
Mode 1 returns only bytes that appear in the string—the easiest output to read and debug.
Use chr($key) to convert a numeric key back to its character.
Example 2 — Loop and Display Each Character (PHP Manual Sample)
This pattern from the official PHP documentation turns the frequency map into readable output.
PHP
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $byte => $count) {
echo "There were $count instance(s) of \"" . chr($byte) . "\" in the string.\n";
}
?>
📤 Output:
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.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.
How It Works
The loop walks every byte that appears at least once. Spaces count too—four spaces appear in this sentence.
📈 Practical Patterns
Mode 0 lookups, unique characters, and real-world checks.
Example 3 — Look Up a Specific Character (Mode 0)
Mode 0 always returns all 256 entries. Use ord() to read the count for one character directly.
Characters appear in ascending byte order, not in the order they first appear in the string. count(count_chars($s, 1)) gives you the number of distinct bytes.
Example 5 — Anagram Detection
Two strings are anagrams when their byte-frequency maps are identical. This is a classic count_chars() use case.
act / cat => anagram: yes
listen / silent => anagram: yes
hello / world => anagram: no
How It Works
PHP compares arrays with ===, checking both keys and values. Anagrams have the same letters in the same quantities—only the order differs. Add strtolower() if you want case-insensitive matching.
Applications
🚀 Common Use Cases
Password validation — require a minimum number of unique characters with count(count_chars($pass, 1)).
Anagram puzzles — compare frequency maps to check if two words use the same letters.
Input validation — verify a string contains only allowed ASCII characters (modes 2 or 4).
Text analysis — find the most frequent letters in a corpus or log file.
Palindrome helpers — analyze character counts when building palindrome checkers.
🧠 How count_chars() Works
1
PHP scans every byte
The function walks the string byte by byte, incrementing a counter for each value from 0 to 255.
Input
2
Frequency table is built
An internal array records how many times each byte value appears in the input string.
Transform
3
Mode filters the output
Depending on mode, PHP returns the full 256-key array, a filtered array, or a string of unique/unused characters.
Output
=
📝
Character insights
Ready for validation, analysis, anagram checks, or debugging.
Important
📝 Notes
count_chars() analyzes bytes, not Unicode code points. Multibyte UTF-8 characters are split into separate byte counts.
Uppercase and lowercase letters are counted separately (A ≠ a).
Mode 0 always returns 256 keys—avoid print_r() on large mode 0 arrays in production logs; use mode 1 instead.
Mode 4 can return a string with hundreds of characters (all bytes not in the input).
For counting one specific substring, use substr_count() instead.
Wrap Up
Conclusion
The count_chars() function is a powerful byte-level analysis tool in PHP. Mode 1 gives you a compact frequency map for everyday use, while modes 3 and 4 produce unique-character strings for validation and puzzles.
Remember it works on raw bytes—perfect for ASCII text, passwords, and anagrams. Pair it with chr() and ord() to move between characters and numeric keys.
Convert keys with chr($byte) when displaying results
Use count(count_chars($s, 1)) for unique character counts
Apply strtolower() when case should not matter
Use mb_* functions for UTF-8 text analysis
❌ Don’t
Dump mode 0 arrays with print_r() in tutorials or logs (256 lines)
Assume it counts Unicode graphemes or emoji as single units
Confuse mode 3 (used chars) with mode 4 (unused chars)
Use count_chars when you only need one substring count
Forget that spaces and punctuation are counted as bytes too
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about count_chars()
Use these points whenever you analyze character frequencies in PHP.
5
Core concepts
📝01
Byte Frequencies
Counts 0–255 bytes.
Purpose
📈02
Mode 1 Best
Compact, readable map.
Syntax
🔄03
chr() / ord()
Key ↔ character.
Helper
📧04
Case Sensitive
A and a differ.
Behavior
⚙05
Anagram Checks
Compare mode 1 maps.
Use case
❓ Frequently Asked Questions
count_chars() counts how many times each byte value (0–255) appears in a string. Depending on the mode, it returns a full frequency array, a filtered array, or a string of unique or unused characters.
array|string count_chars(string $string, int $mode = 0). The $string is analyzed and $mode controls the return format. Mode 1 is the most commonly used for readable frequency maps.
Mode 0 returns all 256 byte frequencies. Mode 1 returns only bytes that appear at least once. Mode 2 returns only bytes with zero count. Mode 3 returns a string of unique characters. Mode 4 returns a string of unused byte characters.
Yes. Uppercase and lowercase letters are different bytes—ord('A') is 65 and ord('a') is 97—so they are counted separately.
No. count_chars() analyzes raw bytes, not Unicode characters. A multibyte UTF-8 character like é is counted as multiple separate byte entries. For Unicode-aware counting, iterate with mb_strlen() and mb_substr().
count_chars() builds a frequency map of every byte in the string. substr_count() counts how many times one specific substring appears. Use count_chars() for full character analysis; use substr_count() to find one needle in a haystack.