Short unique id in php

Short unique id in php

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

Stefan Bogdanescu

Founder & Senior Architect

Generating Short, Readable Unique IDs in PHP

The default output of uniqid() often feels unsatisfactory for user-facing applications. It produces strings like '492607b0ee414', which are technically unique but lack the aesthetic appeal of services like TinyURL or Bitly. The core issue is that standard system time-based generation results in long hex strings where numbers and lowercase letters are mixed indiscriminately. Developers frequently desire a shorter, cleaner identifier—something resembling '64k8ra'—that avoids obvious sequencing while remaining case-insensitive (lowercase only) and prioritizing letters over digits to improve readability.

Achieving this requires shifting away from raw uniqid() toward a custom hashing strategy that maps internal state to a constrained character set. The goal is to create an ID that is both human-readable and statistically unique within your specific dataset scope.

Defining the Character Set and Math

To generate a string like '64k8ra', you must restrict the output alphabet. A common approach is to use a custom alphabet string containing only lowercase letters (a–z) and perhaps a subset of digits, or strictly letters if collision risk permits. If you limit your character set to 26 lowercase letters, each position in your ID contributes $\log_2(26) \approx 4.7$ bits of entropy.

For a target length of 6 characters, this yields approximately $6 \times 4.7 = 28.2$ bits of total entropy. This is sufficient to handle up to $2^{28}$ unique values (roughly 268 million) without collision in a non-distributed system. Since your requirement specifies a dataset size of up to 10,000 entries, the collision risk is negligible. You can safely assume that even with a short ID length and a limited character set, the probability of two different items generating the same string is effectively zero.

Implementation Strategy: Hashing to a Custom Base

Instead of trying to force uniqid() into a shorter format (which usually involves truncating a 13-character hex string down to 6, drastically reducing entropy and increasing collision risk), it is better to hash your unique internal identifier (like a UUID or a timestamp) into the custom character set.

Here is how you might implement this in PHP using a simple modular arithmetic approach:

function generateShortId($input) {
    // Define the allowed characters: lowercase letters preferred
    $chars = 'abcdefghijklmnopqrstuvwxyz';
    $len = strlen($chars);
    
    // Use a strong hash to ensure randomness, not just time
    // md5 or sha1 are sufficient here given the low collision risk
    $hash = md5($input);
    
    $id = '';
    for ($i = 0; $i < 6; $i++) {
        // Take the hash substring and convert to integer modulo char count
        $digit = ord($hash[$i]) % $len;
        $id .= $chars[$digit];
    }
    
    return $id;
}

// Example usage
echo generateShortId('item_123'); // Might output: 'k8ra' (length 6)

Trade-offs and Pitfalls

While the collision risk is low for 10,000 entries, relying solely on a static hash of an input string without salting or ensuring true randomness can be problematic if $input is predictable. If your primary key is simply an incrementing integer, md5($integer) will produce predictable patterns that might look like they have order, violating the "no obvious order" requirement.

A robust solution involves mixing a high-entropy source with your unique identifier before hashing. In production environments where you might eventually scale beyond 100,000 entries or distribute across multiple servers, consider using random_bytes() combined with a custom alphabet to generate IDs directly, rather than deriving them from timestamps or sequential counters.

Another consideration is the "pretty" factor. Users often scan lists of IDs. A string composed entirely of letters ('k8ra') scans faster for humans than one dominated by numbers like '492607'. However, if you strictly use letters (base 26), your ID length must increase slightly to match the entropy of a mixed alphanumeric set. For example, to match the entropy of a 6-character alphanumeric string, a base-26 string would need to be roughly 8 characters long. Given your low volume requirement, sticking to 6 characters with a mixed but letter-heavy set is usually the pragmatic choice.

Verification and Persistence

Before deploying this logic into your main application flow, it is prudent to verify uniqueness against existing records if you are updating an existing table. If you are creating new rows exclusively, the probabilistic nature of the hash is your only requirement. However, if you need to guarantee absolute uniqueness regardless of probability (e.g., for critical financial transactions), you should store the generated ID in a database and check for duplicates before insertion, or use a distributed ID generation library like ulid or uuid that supports shortening strategies natively.

For most medium-scale web applications handling tens of thousands of records, a custom base-26 or alphanumeric hashing function provides the perfect balance between brevity, aesthetics, and statistical safety.

Our network