Short unique id in php

Antti picture Antti · Nov 21, 2008 · Viewed 74.6k times · Source

I want to create a unique id but uniqid() is giving something like '492607b0ee414'. What i would like is something similar to what tinyurl gives: '64k8ra'. The shorter, the better. The only requirements are that it should not have an obvious order and that it should look prettier than a seemingly random sequence of numbers. Letters are preferred over numbers and ideally it would not be mixed case. As the number of entries will not be that many (up to 10000 or so) the risk of collision isn't a huge factor.

Any suggestions appreciated.

Answer

lpfavreau picture lpfavreau · Nov 21, 2008

Make a small function that returns random letters for a given length:

<?php
function generate_random_letters($length) {
    $random = '';
    for ($i = 0; $i < $length; $i++) {
        $random .= chr(rand(ord('a'), ord('z')));
    }
    return $random;
}

Then you'll want to call that until it's unique, in pseudo-code depending on where you'd store that information:

do {
    $unique = generate_random_letters(6);
} while (is_in_table($unique));
add_to_table($unique);

You might also want to make sure the letters do not form a word in a dictionnary. May it be the whole english dictionnary or just a bad-word dictionnary to avoid things a customer would find of bad-taste.

EDIT: I would also add this only make sense if, as you intend to use it, it's not for a big amount of items because this could get pretty slow the more collisions you get (getting an ID already in the table). Of course, you'll want an indexed table and you'll want to tweak the number of letters in the ID to avoid collision. In this case, with 6 letters, you'd have 26^6 = 308915776 possible unique IDs (minus bad words) which should be enough for your need of 10000.

EDIT: If you want a combinations of letters and numbers you can use the following code:

$random .= rand(0, 1) ? rand(0, 9) : chr(rand(ord('a'), ord('z')));