I have a users
table and I need to create a unique, random looking alphanumeric "id" for each user (they already have autoincrementing ids as usually). This identifier must:
AAAA-1234
(4 letters, 4 numbers)Is there a better way than to keep randomly generating strings until I find one that is not in the database yet?
Assign each user an integer in boring old sequential order (or use that other id you mentioned). Call it $x
.
Set $x = (($x + 2135587861) * 2654435769) & 0xffffffff
.
Set $x = $x ^ ($x >> 15)
.
Set $x = (($x + 2135587861) * 2654435769) & 0xffffffff
again.
Calculate $x % 26
and choose a letter a-z based on the result. Set $x = $x / 26
. Repeat four times (I don't know PHP, so you get verbal instructions here).
Calculate $x % 10
and choose a digit 0-9 based on the result. Set $x = $x / 10
. Repeat four times.
First six results I get are:
HSQG-2102
DNQO-1176
TEKJ-5435
EHWX-6540
UPPH-0450
MVIX-5036
It's not exactly perfect, but it's non-obvious. Perhaps that's sufficient.
Also, it only works for the first 4 billion(ish) users before you get collisions, but that's only a little way off of the limit of the string format anyway.