1

Does any one know which of the two choices for random number generation is going to produce a better randomness:

<?php
$array = array(1,2,3,4,5,6);

shuffle($array);
echo $array[0];

//// OR ////

echo rand(1,6);

?>

Or perhaps theres an even better option I am unaware of?

Sir
  • 8,135
  • 17
  • 83
  • 146

2 Answers2

7

Both use the same PRNG so their randomness is equally good/bad. Obviously a plain rand(1,6) is faster since it's just the math and not both the math and the array stuff. Besides that, you'd use array_rand() if you wanted a random element from an array.

PHP also has the mersenne twister (mt_rand()) which is "better" but unsuitable for cryptography (probably not relevant in your case).

If you need true randomness you could consider reading from /dev/random - but that read may block if there's no randomness available. You could also use a hardware device that gives you even better randomness based on some physical effect.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • agreed, the "randomness" is going to be the same. I would look at the processing time if it were only dealing with integers. `rand()` surely would run faster. – Samuel Cook Dec 31 '12 at 18:30
1

On most systems, seed the random number generator with a random value. In most applications, using the low order parts of the current time (like seconds and microseconds) is a pretty good strategy. Whether that works for you depends on the application.

On a Linux system, the program can also read a few bytes from /dev/random or /dev/urandom to seed the random number generator. It is a concentration of random entropy from device drivers and other hard-to-predict phenomena.

wallyk
  • 56,922
  • 16
  • 83
  • 148
  • Seeding the RNG has been unnecessary on most platforms for quite some time now, and in PHP it's been unnecessary since 4.2. – Sammitch Dec 31 '12 at 19:30
  • @Sammitch: Why is that? Is it because the RNG self seeds with the time? – wallyk Dec 31 '12 at 19:38