PHP count_chars() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

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.

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.

📝 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).

⚡ 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

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.

PHP
<?php
$string = "CodeToFun";
$counts = count_chars($string, 1);

print_r($counts);
?>

How It Works

  • Keys are byte values: 67 = C, 111 = o, etc.
  • 111 => 2 means the letter o appears twice.
  • 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";
}
?>

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.

PHP
<?php
$string = "Mississippi";
$all    = count_chars($string, 0);

echo "Total bytes:     " . array_sum($all) . "\n";
echo "Letter 'i' count: " . $all[ord('i')] . "\n";
echo "Letter 's' count: " . $all[ord('s')] . "\n";
echo "Letter 'M' count: " . $all[ord('M')] . "\n";
echo "Array size:      " . count($all) . " keys (always 256)\n";
?>

How It Works

Mode 0 is verbose (256 keys) but lets you look up any byte instantly with $all[ord('x')] without checking if the key exists.

Example 4 — Get Unique Characters (Mode 3)

Mode 3 returns a single string containing every distinct character, sorted by byte value.

PHP
<?php
$words = ["hello", "world", "php"];

foreach ($words as $word) {
    $unique = count_chars($word, 3);
    echo "$word => unique: \"$unique\" (" . strlen($unique) . " chars)\n";
}
?>

How It Works

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.

PHP
<?php
function isAnagram(string $a, string $b): bool
{
    return count_chars($a, 1) === count_chars($b, 1);
}

$pairs = [
    ["act", "cat"],
    ["listen", "silent"],
    ["hello", "world"],
];

foreach ($pairs as [$w1, $w2]) {
    $result = isAnagram($w1, $w2) ? "yes" : "no";
    echo "$w1 / $w2 => anagram: $result\n";
}
?>

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.

🚀 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.

📝 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 (Aa).
  • 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.

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.

💡 Best Practices

✅ Do

  • Use mode 1 for readable frequency maps
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about count_chars()

Use these points whenever you analyze character frequencies in PHP.

5
Core concepts
📈 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.

Explore More PHP String Functions

Continue with crc32(), explode(), and the rest of the string function reference.

Next: crc32() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful