~/docs
Resonate
Resonate
4.x 4.0.0, current 3.x 3.0.1 2.x 2.0.1 1.x 1.3.0
UUID Library
Toggle sidebar
UUID Library
webpatser/uuid 3.0.1
You are reading the 3.x documentation
The current line is 4.x. Read this page for 4.x

UUID Library 3.x

Binary Functions

Convert UUIDs to and from their 16-byte binary form with webpatser/uuid.

A UUID is 128 bits. As a hyphenated string it takes 36 bytes, as a binary string 16. Every Uuid object exposes its binary form, and Uuid::import() reads it back.

To binary

use Webpatser\Uuid\Uuid;
 
$uuid = Uuid::v4();
 
$binary = $uuid->bytes;
echo strlen($binary); // 16
 
// Same bytes, derived from the hex form
var_dump($binary === hex2bin($uuid->hex)); // bool(true)

From binary

Uuid::import() accepts a 16-byte string directly:

$original = Uuid::v4();
$restored = Uuid::import($original->bytes);
 
echo $original->string . "\n";
echo $restored->string . "\n";
var_dump(Uuid::compare($original->string, $restored->string)); // bool(true)

Other formats

$uuid = Uuid::v7();
 
$uuid->string; // "019d05e8-dfa1-7009-a8f7-4e1c868ccfa4"
$uuid->hex; // "019d05e8dfa17009a8f74e1c868ccfa4"
$uuid->bytes; // 16 bytes
$uuid->urn; // "urn:uuid:019d05e8-dfa1-7009-a8f7-4e1c868ccfa4"
Format Size
String with hyphens 36 bytes
Hex without hyphens 32 bytes
Binary 16 bytes

Binary columns

Store $uuid->bytes in a column that holds 16 raw bytes and read it back with Uuid::import():

CREATE TABLE users (
id BINARY(16) PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
$stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (?, ?)');
$stmt->execute([Uuid::v7()->bytes, 'Alice']);
 
$row = $pdo->query('SELECT id, name FROM users')->fetch(PDO::FETCH_ASSOC);
echo Uuid::import($row['id'])->string;

Use v7() for keys you insert often. Its first 48 bits are a millisecond timestamp, so new values sort after older ones.

Binary versus string size

The demo generates 1000 UUIDs with Uuid::v4() and adds up strlen() of the string form and of the binary form: 36,000 bytes against 16,000 bytes. The timings are measured on this server.

1,000 UUIDs from Uuid::v4(), measured on this server just now

String, $uuid->string

36,000 bytes

read in 0.053 ms

Binary, $uuid->bytes

16,000 bytes

read in 0.046 ms

Saved by binary

55.6%

20,000 bytes

First string: 1c54eab7-4101-40be-93d8-48c3df6873d5
Same bytes as hex: 1c54eab7410140be93d848c3df6873d5

Packing several UUIDs

Because every binary UUID has the same length, you can concatenate and split them with plain string functions:

$packed = Uuid::v4()->bytes . Uuid::v4()->bytes;
 
foreach (str_split($packed, 16) as $chunk) {
echo Uuid::import($chunk)->string . "\n";
}

SQL Server

SQL Server stores GUIDs with a different byte order than the one bytes returns. Use toSqlServerBinary() instead, see SQL Server.