Skip to content

Instantly share code, notes, and snippets.

@otar
Created January 4, 2026 09:11
Show Gist options
  • Select an option

  • Save otar/4ea3ec014c9f7ce8dcce407c45bd09f5 to your computer and use it in GitHub Desktop.

Select an option

Save otar/4ea3ec014c9f7ce8dcce407c45bd09f5 to your computer and use it in GitHub Desktop.
PHP convert ULID string to integer
<?php
/*
PHP helper to convert ULID strings to 64-bit integers.
- Minimal collisions
- Deterministic
- Fast and Native
*/
// Let's say we want to determine the correct shard for the record with ULID
$ulid = '01KE43A66G7XBNBZWHSD06DJVX';
$ulidInt = ulidToInt($ulid);
$totalShards = 5;
$shardIndex = $ulidInt % $totalShards;
<?php
/**
* Convert a ULID to a 64-bit integer.
*
* @param string $ulid The ULID string to convert.
* @param int|null $substringPart Optional hex length (1-16) to truncate hash before conversion.
* @return int A 64-bit integer derived from the ULID using FNV-1a hashing.
* @throws RuntimeException If the fnv1a64 hashing algorithm is unavailable.
* @throws InvalidArgumentException If the ULID format or substringPart is invalid.
*/
function ulidToInt(string $ulid, ?int $substringPart = null): int
{
static $hashingAlgorithm = null;
if ($hashingAlgorithm === null) {
$hashingAlgorithm = in_array('fnv1a64', hash_algos(), true);
}
if (!$hashingAlgorithm) {
throw new RuntimeException('The "fnv1a64" hashing algorithm is not available.');
}
$ulid = strtoupper($ulid);
if (strlen($ulid) !== 26 || !preg_match('/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/', $ulid)) {
throw new InvalidArgumentException('Invalid ULID format.');
}
if ($substringPart !== null && ($substringPart < 1 || $substringPart > 16)) {
throw new InvalidArgumentException('substringPart must be between 1 and 16.');
}
$hash = hash('fnv1a64', $ulid);
if ($substringPart !== null) {
$hash = substr($hash, 0, $substringPart);
}
return hexdec($hash);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment