generating random number in PHP

zimu

Diamond Member
Jun 15, 2001
6,209
0
0
hey guys,

can anyone help me generate a random number between 0 and 1 in PHP?

currently using this code:

$num = rand(0, 65536)/65536;

but i feel it can be done in a more efficient/ more "random" way?
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
might want to consider mt_rand(), which is supposedly faster than rand()

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

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

depending on how many decimal places you want in the result, you can adjust the max value and the number to divide the result with

$num = mt_rand (0, 999999) / 1000000;