array_count_values

array_count_values(array $array): array

Counts occurrences of each value in an array, returning a map of value => count (a value histogram). Elements must be int/string; the result keeps first-seen order.

C C23

C23
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *fruits[] = {"apple", "banana", "apple", "cherry", "banana", "apple"};
    size_t n = sizeof fruits / sizeof fruits[0];
    const char *keys[8];
    int counts[8], k = 0;
    for (size_t i = 0; i < n; i++) {
        int j = 0;
        while (j < k && strcmp(keys[j], fruits[i]) != 0) j++; // linear scan for the bucket
        if (j == k) { keys[k] = fruits[i]; counts[k] = 0; k++; }
        counts[j]++;
    }
    printf("{");
    for (int i = 0; i < k; i++) printf("%s\"%s\": %d", i ? ", " : "", keys[i], counts[i]);
    printf("}\n");
    return 0;
}
Output
{"apple": 3, "banana": 2, "cherry": 1}

C++ C++26

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

int main() {
    std::vector<std::string> fruits = {"apple", "banana", "apple", "cherry", "banana", "apple"};
    std::map<std::string, int> hist; // a sorted map iterates deterministically
    for (const auto &f : fruits) hist[f]++;
    std::cout << "{";
    bool first = true;
    for (const auto &[k, c] : hist) {
        std::cout << (first ? "" : ", ") << '"' << k << "\": " << c;
        first = false;
    }
    std::cout << "}\n";
    return 0;
}
Output
{"apple": 3, "banana": 2, "cherry": 1}

C# v11.0.100

v11.0.100
var fruits = new[] { "apple", "banana", "apple", "cherry", "banana", "apple" };
var hist = fruits.GroupBy(f => f) // GroupBy keeps first-seen group order
                 .ToDictionary(g => g.Key, g => g.Count());
Console.WriteLine("{" + string.Join(", ", hist.Select(kv => $"\"{kv.Key}\": {kv.Value}")) + "}");
Output
{"apple": 3, "banana": 2, "cherry": 1}

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sort"
)

func main() {
	fruits := []string{"apple", "banana", "apple", "cherry", "banana", "apple"}
	hist := map[string]int{}
	for _, f := range fruits {
		hist[f]++
	}
	keys := make([]string, 0, len(hist))
	for k := range hist {
		keys = append(keys, k)
	}
	sort.Strings(keys) // Go map iteration is unordered: sort for reproducible output
	fmt.Print("{")
	for i, k := range keys {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Printf("%q: %d", k, hist[k])
	}
	fmt.Println("}")
}
Output
{"apple": 3, "banana": 2, "cherry": 1}

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = List.of("apple", "banana", "apple", "cherry", "banana", "apple");
        Map<String, Integer> hist = new LinkedHashMap<>(); // first-seen order, reproducible
        for (String f : fruits) {
            hist.merge(f, 1, Integer::sum); // merge increments in one call
        }
        System.out.println(hist);
    }
}
Output
{apple=3, banana=2, cherry=1}

JavaScript v26.13.1

v26.13.1
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const hist = {};
for (const f of fruits) hist[f] = (hist[f] ?? 0) + 1; // object keys follow first-seen insertion order
console.log(JSON.stringify(hist));
Output
{"apple":3,"banana":2,"cherry":1}

PHP v8.6.0

v8.6.0
$fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
// counted values become the keys; the result keeps first-seen order
echo json_encode(array_count_values($fruits)), "\n";
Output
{"apple":3,"banana":2,"cherry":1}

Python v3.15.2

v3.15.2
from collections import Counter

fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]
hist = Counter(fruits)  # a dict subclass: value -> count, first-seen key order
print(dict(hist))
Output
{'apple': 3, 'banana': 2, 'cherry': 1}

Rust v1.99.1

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

fn main() {
    let fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
    let mut hist: BTreeMap<&str, usize> = BTreeMap::new(); // sorted keys: deterministic output
    for f in fruits {
        *hist.entry(f).or_insert(0) += 1; // the entry API increments in place
    }
    print!("{{");
    for (i, (k, c)) in hist.iter().enumerate() {
        if i > 0 {
            print!(", ");
        }
        print!("{:?}: {}", k, c);
    }
    println!("}}");
}
Output
{"apple": 3, "banana": 2, "cherry": 1}

TypeScript v26.13.1

v26.13.1
const fruits: string[] = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const hist: Record<string, number> = {};
for (const f of fruits) hist[f] = (hist[f] ?? 0) + 1; // Record keys follow first-seen insertion order
console.log(JSON.stringify(hist));
Output
{"apple":3,"banana":2,"cherry":1}

Language differences

C: no built-in hash table — parallel arrays plus a linear bucket scan, printed in first-seen order.

C++: a 'std::map' iterates in sorted order, so the output is naturally deterministic; counting is just 'hist[f]++' (default 0).

C#: LINQ 'GroupBy' is the direct counterpart, groups in first-seen order.

Go: the map must be counted first, then its keys sorted before printing (map iteration order is random).

Java: 'Map.merge' counts in one call; 'LinkedHashMap' keeps first-seen order; Streams 'groupingBy' is the alternative (its default HashMap is unordered, so pass LinkedHashMap explicitly).

JavaScript: object keys follow first-seen insertion order; a 'Map' generalizes to arbitrary key types.

PHP: the counted values become the result keys — so only int/string elements are allowed (anything else raises E_WARNING and is skipped); key stringification merges '1' with string '1' into one entry; the result keeps first-seen order.

Python: 'collections.Counter' is the native counterpart (a dict subclass); 'most_common()' gives Top-N directly.

Rust: 'BTreeMap' + the 'entry' API; 'itertools::counts()' is the one-liner idiom (third-party crate).

TypeScript: same as JavaScript, annotated as 'Record<string, number>'.