Take the 2-minute tour ×

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

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

echo $array[0];

//// OR ////

echo rand(1,6);


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

share|improve this question
shuffle() uses the same generator as rand() - stackoverflow.com/questions/5694319/… –  ncremins Dec 31 '12 at 18:30
I just rolled a 4 with my six-sided dice. Feel free to use that - all I ask is credit. –  Mike B Dec 31 '12 at 18:37
"Better" in what sense? It's really hard to figure out what you're looking for here. –  David Schwartz Dec 31 '12 at 19:01
Do what Sony does: DEFINE('rand()', 3); –  Sammitch Dec 31 '12 at 19:28

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
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

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.

share|improve this answer
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

Your Answer


