PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hi,
I need help in generating unique number using php.I tired using rand() in php.But, by using rand() method,the generated values are repeating.I want unique numbers in my application.
Every time in loop,i need a unique number.
If anybody knows of generating unique numbers,pls reply AEAP.
madhurima wrote:Hi,
I need help in generating unique number using php.I tired using rand() in php.But, by using rand() method,the generated values are repeating.I want unique numbers in my application.
Every time in loop,i need a unique number.
If anybody knows of generating unique numbers,pls reply AEAP.
Thank u inadvance,
madhu
Many ways to combine functions to get unique numbers. Here are two functions:
mt_rand() and uniqid()
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Neither srand(), rand(), mt_rand(), nor uniqid() are guaranteed to give you a unique number. The chance of collision for all of those is pretty low, but not 100%. The only way to guarantee you aren't duplicating a random number is to store the numbers you have already generated, then check against them.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
pickle wrote:Neither srand(), rand(), mt_rand(), nor uniqid() are guaranteed to give you a unique number. The chance of collision for all of those is pretty low, but not 100%. The only way to guarantee you aren't duplicating a random number is to store the numbers you have already generated, then check against them.
And they aren't 'random' in the true sense of the word, but who cares really?