MrPizzaFace
MrPizzaFace

Reputation: 8086

PHP semi-random string generator

How to make my id generator code elegant: When a user registers they get an id.. What is the chance that the id generated will NOT be unique? Also - How can i make my code elegant? THANKS!

#hash = random url generated from 128 chars

$cac = substr($hash, 64,-60);

$words = array('GET', 'COOL', 'WOW', 'YES', 'NICE', 'BUCK', 'LUCK', 'FUN', 'CASH', 'TIP', 'PEEK', 'TAG'); 
$rword = rand(0,11);

$syms = array('-', '#', '$', '@');
$rsym = rand(0,3); 

$nums = rand(0,9);

$aff_id_temp = $words[$rword] . $syms[$rsym] . $cac . $nums;
$final_id = strtoupper($aff_id_temp);

---UPDATE--- The code works. Just need to generate a simple affiliate id for users when they register. By elegant I mean – perhaps the way I am hacking out the final product code be done more simply or in a different way (perhaps in a loop) basically I want to learn different ways to achieve the same result. I want other coding perspectives.

The output is something like: TIP#6C1D2

Upvotes: 1

Views: 296

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Practically zero, due to the hash. That said, it depends entirely on the hash function.

Excluding the hash, the chance of any given id colliding with another given id is 1/(12*4*10) = 1/480, roughly 0.2%. However, the chance of a new id not colliding with any other id is 1-(1-1/480)^c, where c is the number of ids you already have. With just 50 ids you already have a 10% chance of collision.

You can get a unique hash with the uniqid function.

Upvotes: 1

Related Questions