count_chars

count_chars(string $string, int $mode = 0): array|string

Byte-level string statistics: mode 0 full table / 1 present only / 2 absent only / 3 present as string / 4 absent as string - a 256-slot byte histogram.

C C23

C23
#include <stdio.h>

/* the byte histogram PHP's mode 0 builds: 256 counters */
int main(void) {
    const char *s = "hello";
    int counts[256] = { 0 }; /* zeroed! */
    for (int i = 0; s[i]; i++) counts[(unsigned char)s[i]]++;
    printf("%d %d %d\n", counts['h'], counts['l'], counts['z']);
    return 0;
}
Output
1 2 0

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>

int main() {
    std::string s = "hello";
    std::map<char, int> counts; // keys stay sorted - deterministic
    for (char c : s) counts[c]++;
    for (const auto& [ch, n] : counts)
        std::cout << ch << "=" << n << "\n";
    return 0;
}
Output
e=1
h=1
l=2
o=1

C# v11.0.100

v11.0.100
using System.Linq;

class MainClass {
    static void Main() {
        string s = "hello";
        // GroupBy counts characters; OrderBy keeps the output deterministic
        var parts = s.GroupBy(c => c)
            .OrderBy(g => g.Key)
            .Select(g => g.Key + "=" + g.Count());
        System.Console.WriteLine(string.Join(" ", parts));
    }
}
Output
e=1 h=1 l=2 o=1

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {
	s := "hello"
	counts := map[byte]int{}
	for i := 0; i < len(s); i++ {
		counts[s[i]]++
	}
	// map iteration order is random - sort keys for stable output
	keys := make([]byte, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
	parts := make([]string, 0, len(keys))
	for _, k := range keys {
		parts = append(parts, fmt.Sprintf("%c=%d", k, counts[k]))
	}
	fmt.Println(strings.Join(parts, " "))
}
Output
e=1 h=1 l=2 o=1

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) {
        String s = "hello";
        int[] counts = new int[256]; // zeroed by Java
        for (int i = 0; i < s.length(); i++) counts[s.charAt(i)]++;
        // scan the full table like PHP's mode 0
        List<String> parts = new ArrayList<>();
        for (int b = 0; b < 256; b++)
            if (counts[b] > 0) parts.add((char) b + "=" + counts[b]);
        System.out.println(String.join(" ", parts));
    }
}
Output
e=1 h=1 l=2 o=1

JavaScript v26.13.1

v26.13.1
const s = "hello";
const counts = {};
for (const ch of s) counts[ch] = (counts[ch] ?? 0) + 1;

// object key order: insertion - sort for determinism
console.log(
  Object.keys(counts).sort().map(k => `${k}=${counts[k]}`).join(" ")
);
Output
e=1 h=1 l=2 o=1

PHP v8.6.0

v8.6.0
$s = "hello";

echo json_encode(count_chars($s, 1)), "\n"; // byte => count, only present
echo count_chars($s, 3), "\n";              // present chars as a sorted string
echo strlen(count_chars($s, 4)), "\n";      // 256 - 4 absent bytes = 252
$t = count_chars($s, 0);                    // full 256-slot table
echo $t[ord("h")], " ", $t[ord("z")], "\n";  // 1 0
Output
{"101":1,"104":1,"108":2,"111":1}
ehlo
252
1 0

Python v3.15.2

v3.15.2
from collections import Counter

s = "hello"
c = Counter(s)
# Counter is exactly PHP's mode 1: only present items, with counts
print(dict(sorted(c.items())))
print("".join(sorted(c)))   # mode 3 equivalent
print(len(c))               # distinct count
Output
{'e': 1, 'h': 1, 'l': 2, 'o': 1}
ehlo
4

Rust v1.99.1

v1.99.1
use std::collections::BTreeMap;

fn main() {
    let s = "hello";
    let mut counts: BTreeMap<char, i32> = BTreeMap::new();
    for c in s.chars() {
        *counts.entry(c).or_insert(0) += 1;
    }
    // BTreeMap keeps keys sorted - deterministic by construction
    let parts: Vec<String> = counts
        .iter()
        .map(|(ch, n)| format!("{}={}", ch, n))
        .collect();
    println!("{}", parts.join(" "));
}
Output
e=1 h=1 l=2 o=1

TypeScript v26.13.1

v26.13.1
const s = "hello";
const counts: Record<string, number> = {};
for (const ch of s) counts[ch] = (counts[ch] ?? 0) + 1;

// insertion order is not a determinism guarantee - sort for stability
console.log(
  Object.keys(counts).sort().map(k => `${k}=${counts[k]}`).join(" ")
);
Output
e=1 h=1 l=2 o=1

Language differences

C: int counts[256] = {0} IS PHP's mode 0 (example) - the byte histogram is C's most natural counting shape; the (unsigned char) cast avoids sign-extension UB; ZERO IT - stack garbage flows straight into the results otherwise.

C++: std::map<char,int> (example) keeps key order deterministic; for PHP's 256-slot full-table shape use std::array<int,256>; if char is signed, cast to unsigned char before indexing, same as C.

C#: LINQ GroupBy + OrderBy (example); C# strings are UTF-16 code units, GroupBy(c => c) counts characters not bytes - closer to the character intuition than PHP's byte view; a concurrent-collection variant suits parallel work.

Go: map[byte]int + sort (example) - Go map order is random, sorting is mandatory; for range s iterates bytes (ASCII-safe), for _, r := range s iterates runes for Unicode.

Java: int[256] + full-table scan (example) - isomorphic to PHP's mode 0; Java chars are UTF-16, astral characters split into surrogate pairs - use HashMap<Character,Integer> for true Unicode counting.

JavaScript: hand-written object counting (example); ?? handles first occurrence; JS strings iterate by code unit - emoji and other astral characters split, so for...of iterates code points; no built-in Counter.

PHP: the five-mode spectrum (the example covers 0/1/3/4): mode 0 is the full 256-slot table, 1 present only, 2 absent only, 3/4 string forms; BYTE view - UTF-8 multibyte characters are counted per byte, use the mb_* family for Chinese text; mode 1's keys are byte codes (readable for ASCII, opaque above), and json_encode turns them into numeric strings.

Python: collections.Counter is the perfect mode 1 counterpart (example); Counter has no mode 0 shape (only present keys); most_common(n) frequency ranking is Counter's exclusive ability; Python counts code points - no byte-view confusion.

Rust: BTreeMap keeps keys ordered by construction (example), HashMap would need sorting; entry().or_insert(0) is the idiomatic counting pattern; chars() iterates code points, unlike PHP's byte view.

TypeScript: same as JS (example); Record<string, number> closes the type; the JS code-point iteration difference applies to emoji here too.