UUID interop
A ULID and a UUID are the same 128 bits in different encodings.
use Webpatser\Ulid\Ulid;use Webpatser\Uuid\Uuid; // ULID → UUID (same 128-bit value, different encoding)$ulid = Ulid::generate();$uuid = $ulid->toUuid();echo $uuid->string; // e.g. "019d05e8-dfa1-7009-a8f7-4e1c868ccfa4" // UUID → ULID$uuid = Uuid::v7();$ulid = Ulid::fromUuid($uuid);echo (string) $ulid; // e.g. "01KM...", a fresh value on every run
Binary storage
ULIDs are 16 bytes in binary, same as UUIDs. That suits BINARY(16) database columns.
use Webpatser\Ulid\Ulid; $ulid = Ulid::generate();$binary = $ulid->toBytes(); // 16 bytes for storage$ulid = Ulid::fromBytes($binary); // Restore from binary
Timestamp extraction
use Webpatser\Ulid\Ulid; $ulid = Ulid::generate();$timestamp = $ulid->getTimestamp(); // DateTimeImmutable$ms = $ulid->getTimestampMs(); // e.g., 1773920640936
Generate with a fixed time
The test suite round-trips a custom time through getTimestamp().
use Webpatser\Ulid\Ulid; $time = new DateTimeImmutable('2024-01-15 12:00:00.000', new DateTimeZone('UTC'));$ulid = Ulid::generate($time); echo $ulid->getTimestamp()->format('Y-m-d H:i:s'); // 2024-01-15 12:00:00 (getTimestamp() always returns UTC)
Monotonic ordering
ULIDs generated within the same millisecond increment the random portion, so they sort in creation order.
use Webpatser\Ulid\Ulid; $ulids = [];for ($i = 0; $i < 100; $i++) { $ulids[] = (string) Ulid::generate();} $sorted = $ulids;sort($sorted); var_dump($ulids === $sorted); // bool(true)
Note: If the 80-bit random portion overflows within one millisecond,
generate()throws aRuntimeExceptionwith the messageULID monotonic counter overflowinstead of wrapping to zero.