hichxm / hyperloglog
A PHP implementation of the HyperLogLog algorithm.
Requires
- php: ^7.0|^7.1|^7.2|^7.3|^7.4|^8.0|^8.1|^8.2|^8.3|^8.4|^8.5
Requires (Dev)
- php-cs-fixer/shim: ^3.95
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^9.6|^8.5|^6.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A lightweight, dependency-free PHP implementation of the HyperLogLog probabilistic data structure for estimating the number of distinct values in a large stream using a fixed number of registers.
HyperLogLog trades exactness for low, predictable memory use. Use it when an approximate distinct count is acceptable;
use an exact set or database COUNT(DISTINCT ...) when it is not.
Features
- Estimate distinct cardinality with memory determined by the configured register count, not the number of values seen.
- Tune the accuracy/memory trade-off with
counterBits. - Choose any hash algorithm supported by PHP's
hash()function. - Merge compatible sketches to estimate the cardinality of a union.
- Get the theoretical relative standard error for a chosen register count.
- No runtime Composer dependencies.
Requirements
- PHP 7.0 or later in the supported PHP 7.x/8.x series. The project CI currently tests PHP 7.0 through 8.5.
- A hash algorithm available in the current PHP build.
The default hash algorithm is xxh3, which may not be available in every PHP version or build. Use an algorithm returned by
hash_algos(); sha256 is a portable alternative.
Installation
Install the library with Composer:
composer require hichxm/hyperloglog
Quick start
<?php use Hichxm\HyperLogLog\HyperLogLog; require __DIR__ . '/vendor/autoload.php'; // sha256 is available on a wide range of PHP builds. $hll = new HyperLogLog(10, 'sha256'); $hll->add('user-101'); $hll->add('user-205'); $hll->add('user-101'); // Adding a duplicate does not add another distinct value. printf("Estimated distinct users: %d\n", $hll->count());
count() returns an integer estimate, not an exact count. The example's result should be close to 2.
Accuracy and memory
With m registers, the theoretical relative standard error is approximately:
1.04 / sqrt(m), where m = 2^counterBits
Increasing counterBits allocates more registers and generally improves accuracy. These figures describe the theoretical
standard error; they are not a per-dataset guarantee.
counterBits |
Registers (m) |
Theoretical relative standard error |
|---|---|---|
| 4 | 16 | 26% |
| 5 (default) | 32 | 18.4% |
| 10 | 1,024 | 3.25% |
| 12 | 4,096 | 1.625% |
For example, configure 1,024 registers and choose a hash algorithm explicitly:
$hll = new HyperLogLog(10, 'sha256'); $registerCount = $hll->getM(); // 1024 $errorRate = $hll->theoreticalErrorRate($registerCount); // approximately 0.0325 (3.25%)
The library also exposes theoreticalErrorRate(int $m) directly. Pass the sketch's register count ($hll->getM()), not
counterBits.
Hash algorithms
The constructor accepts an algorithm supported by the running PHP installation. Discover available choices with:
print_r(hash_algos());
Common choices include xxh3, xxh128, sha256, sha512, sha1, and md5, subject to PHP build support. The default is
xxh3. Short hash outputs are padded internally before the implementation reads the hash bits.
Use the same algorithm and register configuration for sketches that you intend to merge.
Merging sketches
merge() updates the receiving sketch register-by-register using the maximum value from each sketch. This produces a
sketch of the union of the represented sets; it does not add their estimated counts together.
$north = new HyperLogLog(12, 'sha256'); $south = new HyperLogLog(12, 'sha256'); foreach ($northUserIds as $userId) { $north->add((string) $userId); } foreach ($southUserIds as $userId) { $south->add((string) $userId); } $north->merge($south); $estimatedUniqueAcrossBothRegions = $north->count();
Both sketches must use the same number of registers and the same hash algorithm. A mismatch throws
InvalidArgumentException. merge() mutates the receiving object and returns it, so calls can be chained.
Constructor
new HyperLogLog(int $counterBits = 5, string $hashAlgorithm = 'xxh3');
counterBits: number of bits used to select registers; the sketch contains2^counterBitsregisters. More bits use more memory and reduce the theoretical error.hashAlgorithm: an algorithm supported by PHP'shash()function. Select an available algorithm explicitly if the defaultxxh3is unavailable in your environment.
An unavailable algorithm causes InvalidArgumentException during construction.
API reference
| Method | Description |
|---|---|
add(string $value) |
Add one string value to the sketch. |
count(): int |
Return the estimated distinct cardinality as an integer. |
merge(HyperLogLog $other): self |
Merge a compatible sketch into this one; mutates and returns this sketch. |
getCounterBits(): int |
Return the configured counterBits. |
getHashAlgorithm(): string |
Return the selected hash algorithm. |
getM(): int |
Return the number of registers (2^counterBits). |
getCounters(): array |
Return the register values. Intended mainly for inspection and advanced use. |
setCounters(array $counters): self |
Replace register values. Advanced/low-level method; the caller must provide a valid register array of the correct size. |
theoreticalErrorRate(int $m): float |
Return the theoretical relative standard error for m registers (1.04 / sqrt(m)). |
measureError(int $estimate, int $real): int |
Return the signed difference estimate - real; this is neither an absolute nor percentage error. |
The implementation also exposes lower-level estimator helpers: alpha(int $m), estimate(int $m, float $Z),
estimateUsingLinearCounting(int $V, int $m), estimateUsingSmallCardinalitiesApproach(int $V, int $m), and
estimateUsingLargeCardinalitiesApproach(float $E). These are primarily useful for advanced integrations and testing.
theoreticalErrorRate() and alpha() require m > 0; estimate() requires a positive harmonic sum Z. They throw
InvalidArgumentException when those inputs are invalid. setCounters() does not validate the supplied register array,
so malformed state can cause incorrect results or runtime errors.
Development and tests
Install development dependencies and run the test suite:
composer install
composer test
Run the full local checks (code style, static analysis, and tests):
composer check-all
License
MIT