How can I generate a 6 digit unique number?

How can I generate a 6 digit unique number?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating 6-Digit Unique Numbers: Strategy and Implementation

Generating a six-digit unique number is a common requirement for verification codes, session tokens, or simple identifiers. The constraint of exactly six digits immediately defines your solution space to the range 000000 through 999999, offering a total pool of one million possible combinations. Whether you need this for an SMS OTP, a temporary login token, or a reference ID, the approach depends heavily on how you define "unique."

If your system relies solely on database-level constraints to enforce uniqueness—such as a CHECK constraint or a unique index on the generated column—you can safely use a random generation strategy. This method is statistically robust provided you do not exhaust the entire space. With one million possibilities, hitting a collision becomes practically impossible unless you are generating millions of tokens per second without any cleanup mechanism.

Here is how to implement this in PHP using the standard extension:

function generateSixDigitCode(): string {
    $min = 0;
    $max = 999999;
    
    // Ensure we always get a 6-digit string, including leading zeros
    return str_pad((string)rand($min, $max), 6, '0', STR_PAD_LEFT);
}

The str_pad function is critical here. A raw random integer between 0 and 999999 might return 12345, which visually fails the "6-digit" requirement unless you explicitly pad it with leading zeros. For verification codes, visual consistency matters; a user expecting 012345 will be confused if they receive just 12345.

However, relying purely on randomness introduces a specific edge case: collisions. Even with one million combinations, there is a non-zero probability that two requests occur simultaneously and generate the same number before either hits your database check. If your application architecture assumes "generate then insert," and the insert fails due to a duplicate key error, you are left handling the rollback or retry logic.

To eliminate race conditions entirely without depending on database transactions for every single generation step, you can shift the responsibility of uniqueness to the identifier itself. Instead of generating a random number and checking if it exists, you generate a sequential ID within the six-digit limit. This is often faster because it avoids any I/O wait time associated with duplicate checks during the generation phase.

function generateSequentialSixDigitCode($nextId): string {
    $min = 0;
    $max = 999999;
    
    // Ensure the value stays within the 6-digit limit
    $value = min($nextId, $max);
    
    return str_pad((string)$value, 6, '0', STR_PAD_LEFT);
}

In this scenario, $nextId is typically fetched from an atomic counter in your database or cache store. You increment it only after successfully committing the record associated with that code. This guarantees uniqueness by definition, as each integer maps to exactly one string representation within the padded range.

The trade-off between these two approaches is operational complexity versus statistical probability. The random approach feels more "secure" to some because it doesn't look predictable, but for non-security-critical identifiers like verification codes, predictability is irrelevant. What matters is that the number hasn't been used recently.

If you are building this on a Laravel application, you might consider leveraging existing packages or built-in utilities if you need higher entropy than rand() provides, such as using Random\Randomizer from the framework's random utility classes for better cryptographic security properties. However, for standard verification codes where ease of use and readability are prioritized over cryptographic strength, the simple padded integer approach remains sufficient.

Always remember that a six-digit code has a finite lifespan if you treat it as a counter. Once you hit 999999, you must either reset the counter (which risks collisions) or expand your digit count. If your volume exceeds one million requests per day, generating six digits is no longer sustainable without a reset strategy that accepts the risk of temporary duplicates.

Our network