-1

I'm messing around with the rand() function and have been wondering if it will ever repeat? Not sure if this is really a good question to put on so but I'll post it anyway, thanks.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • 1
    yes it will, its random, **not unique** –  Feb 24 '15 at 19:53
  • http://en.wikipedia.org/wiki/Pseudorandom_number_generator – Stefan Feb 24 '15 at 19:53
  • 1
    @Dagon So, somthing like `unique_id` will always be completely random? – Joe Scotto Feb 24 '15 at 19:54
  • nooooooo uniqueid is NOT random –  Feb 24 '15 at 19:55
  • 1
    **"Warning This function does not create random nor unpredictable strings. This function must not be used for security purposes. Use a cryptographically secure random function/generator and cryptographically secure hash functions to create unpredictable secure IDs. "** http://php.net/manual/en/function.uniqid.php –  Feb 24 '15 at 19:56
  • 1
    `for($i = 1; $i <= 3; $i++) { echo rand(1,2); }` and figure out the answer for yourself – Mark Baker Feb 24 '15 at 19:57
  • 1
    @Dagon What can I do to get a completely random string that will never repeat? – Joe Scotto Feb 24 '15 at 19:58
  • If I roll a dice 6 times, is there any possibility that I'll get the same number coming up twice? – Mark Baker Feb 24 '15 at 19:58
  • possible duplicate of [PHP: How to generate a random, unique, alphanumeric string?](http://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string) –  Feb 24 '15 at 19:58
  • i wish you just asked that in the first place! –  Feb 24 '15 at 19:59
  • use openssl_random_pseudo_bytes()... – Halayem Anis Feb 24 '15 at 19:59
  • You could: Generate random string, attempt to insert into table with unique constraint, if it fails, do it again. – developerwjk Feb 24 '15 at 20:06

2 Answers2

1

Yes, it will repeat. There is a limit to the number of possibilities. From the docs:

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

You can print out getrandmax() to see what that number is on your system, but its probably 32767. So if you call rand() 32767 times, you will definitely get repetition. Call it less than that number of times, you most likely will as well, but for lower amount of calls (less than 100 say) its less likely to get repetition, although it can certainly happen.

developerwjk
  • 8,619
  • 2
  • 17
  • 33
-2

It's good to know nothing can be unique, UT close to unique. If you're searching for something very unique, you should search up on uuid, it's a standard for a ids that is pretty long and therefore also very unique.

Jesper
  • 3,816
  • 2
  • 16
  • 24