PHP.GT

Custom lengths and timestamp sections

The library defaults to a 20-character identifier:

  • 10 characters for the timestamp
  • 10 characters for the random section

That is a sensible default for most applications, but both parts can be configured when a different trade-off makes more sense.

Changing the total length

use GT\Ulid\Ulid;

$id = new Ulid(length: 30);
echo $id;
echo strlen((string)$id);

Increasing the total length gives the identifier a longer random section, because the timestamp section remains at its default length unless we change that too.

Changing the timestamp section length

$id = new Ulid(timestampLength: 8);
echo $id->getTimestampString();

This changes how much of the encoded timestamp is exposed at the front of the string.

Changing both together

$id = new Ulid(length: 24, timestampLength: 12);

This gives us explicit control over the balance between:

  • how much room is allocated to time ordering
  • how much room is allocated to randomness
  • how long the final ID should be in storage and interfaces

When to customise

Custom lengths can be useful when:

  • a legacy schema has a strict column length
  • an external format expects a particular identifier width
  • we want longer random sections for application-specific reasons

One important rule

Once an application is using a particular ULID shape in production data, changing that shape mid-stream should be a deliberate migration decision.

For example, if one part of the system expects:

01KPKT4PFTKVQ9P1E72F

and another suddenly starts producing a different layout, any code that validates length or slices sections by position will need to change at the same time.

Matching Extractor to customised IDs

If we are parsing ULIDs with non-default lengths, construct Extractor with matching values:

use GT\Ulid\Extractor;

$extractor = new Extractor(
	length: 24,
	timestampLength: 12,
);

That keeps the extractor aligned with the IDs our application is producing.


For the encoding rules underneath these sections, move on to Base32 encoding.