Skip to content
Digital Garden
Library

Counting Chars Natively in PHP using count_chars()

A quick PHP optimization story — from str_split() and manual loops to count_chars(), a native function that offloads character counting to C.

PHP Perf Glow-Up LeetCode Grind

Last tended


Last year when I was actively grinding leetcode problems, I used to reach for str_split() whenever I needed to count characters in a string. Which is perfectly fine, but I didn’t realize that PHP has a built-in function called count_chars() that can be used to count the number of characters in a string.

The problem I was facing was, I needed to count the frequency of each character in a string.

Here’s the problem’s description:

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example 1: Input: ransomNote = "a", magazine = "b" Output: false

Example 2: Input: ransomNote = "aa", magazine = "ab" Output: false

Example 3: Input: ransomNote = "aa", magazine = "aab" Output: true

My initial solution was like this:

Very rough, isn’t it? But it does the job very well and I got the point. The thing is, it takes 24ms and consumes 22.18 MB. I only beat 13.64% of around 2 million accepted solutions. That means my rank was around 1.7 million. 😑
I wonder if there’s a better solution for this. 🤔

So I started to plunge into the PHP documentation to find better alternatives. Until I found this function called count_chars().

If you look at my initial solution, I was using str_split() to break the string into individual chars, then looping through the result to count them. This isn’t efficient at all — str_split() has to allocate a whole new array just to hold those chars before I can even start counting.

When you pass "aaa" into str_split(), it returns ['a', 'a', 'a'] and that’s it. But when the string gets larger, it consumes more memory.

PHP provides a low-level function for character counting: count_chars(). Instead of looping and counting manually, it delegates the whole process to C (Zend Engine) and hands back an associative array of character counts — no manual loop, no extra array to allocate. This drastically simplifies how I count the number of unique characters!

Note

count_chars() counts bytes, not characters. For this problem that’s fine — the constraints only allow lowercase English letters, and every ASCII letter is exactly 1 byte. But if your string has multi-byte UTF-8 characters (emoji, accented letters, non-Latin scripts), count_chars() will count each byte separately instead of each character — so it’ll overcount anything outside plain ASCII.

The second argument, mode, controls the shape of that return value. Passing 1 (like I did) tells it to only include characters that actually appear at least once — skip the mode and it defaults to 0, which returns all 256 byte values whether they appear or not.

So, here’s my latest solution which grants me 0ms exec time and 20.4 MB memory consumption. I beat 100.00% of the solutions! 🎉


Moral of the story

Writing code that works is easy. Writing code that works with the tools you already have — that’s the real work of an engineer.