1

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

3
  • Define what you mean by elegant. Be specific what the problem is. It would also help to have some context as to what you are trying to do, and expected output. Commented Sep 6, 2012 at 17:13
  • How about: md5( $salt . $user['email'] ); Commented Sep 6, 2012 at 17:16
  • Updated question.. @HappyTimeGopher im not concerned with my $hash -> I'm more interested in different ways to obtain my $final_id Commented Sep 6, 2012 at 17:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

My hash is being generated using a rand1,1B and then hash of SHA512 -- How does my HASH effect your equation?
Besides the HASH I'm more interested in the $final_id -> How else could you get to the same result. I feel like their are more "elegant" or different solutions. THANKS FOR THE HELP!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.