Generating a random number in PHP is very simple and like most things, can be done a number of different ways. The old standby is to use the function rand() to to generate a random integer between the minimum and maximum values that you provide. To generate a number between 1 and 100 you would do this:

$random = rand(1, 100);

At this point, rand() basically exists for backwards compatibility’s sake. The newer / preferred function to use is mt_rand() which addresses speed concerns with the former and clocks in at 4 times faster. The “MT” in the name referred to Mersenne Twister which is an alternative random number generator to libcs. You use this function in the same way:

$random = mt_rand(1, 100);

This is great for generating random integers, but what if you want a random decimal value? There’s actually not a function to do so, but you could easily divide a random number by a larger number or slap a decimal at the beginning of the value to achieve the desired results.

On a side note, as of PHP 4.2.0 you no longer need to concern yourself with seeding the random number generator (hence why it wasn’t mentioned here ;)

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: