UUID v7 Generator (Time-Ordered) in Pure PHP
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
UUIDv4 is fully random, which means consecutive inserts scatter across a B-tree index and fragment it. UUIDv7 fixes that by putting a millisecond timestamp in the high bits, so values generated close in time sort close together, giving you the database-friendly locality of an auto-increment id while keeping global uniqueness and unguessability. This is the version you want for primary keys in 2026.
The layout is 48 bits of Unix time in milliseconds, then 4 version bits set to 7, then 12 random bits, then 2 variant bits, then 62 more random bits. The function below packs the timestamp as 12 hex characters, fills the rest from random_bytes for cryptographic quality, and masks the version nibble and the variant byte into place. No extension and no library required.
function uuidv7(): string {
$ms = (int) (microtime(true) * 1000);
$tsHex = str_pad(dechex($ms), 12, '0', STR_PAD_LEFT);
$rand = random_bytes(10);
$rand[0] = chr((ord($rand[0]) & 0x0f) | 0x70); // version 7
$rand[2] = chr((ord($rand[2]) & 0x3f) | 0x80); // variant 10
$hex = $tsHex . bin2hex($rand);
return sprintf('%s-%s-%s-%s-%s',
substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4),
substr($hex, 16, 4), substr($hex, 20, 12));
}
$a = uuidv7();
$b = uuidv7();
echo $a . "\n" . $b . "\n";
echo "sorted in generation order: " . ($a <= $b ? 'yes' : 'no') . "\n";
Comments
No comments yet
Be the first to share your thoughts!