Generate Random Unique Number

I have found many times when writing stuff in PHP that I have come across a need to generate a random number. That’s not too bad in and of itself, but what about when you need a unique ID key or something like that. For example, say you are writing the next best helpdesk application and need unique case numbers and don’t want to simply use a counter. For whatever reason, I put this little function together and it has served me well. Check it out …

Here you can see that I am using time and date down to the seconds to make sure I have some unique numbers in there. I am sure there are lots of ways to accomplish the same thing, and probably more elegantly as well, but this has worked for me and I wanted to share!

// This generates a unique key or id
function genkey() {
 $rnd = rand(1000,9999);
 $seed = date("Ydmis");
 return $seed.$rnd;

Hope you find it useful, enjoy!

Tell me what you are thinking?