Faster Random Numbers with PHP

Random numbers functions rand() and mt_rand are easy to use and pretty fast. Numbers produced by these functions range from 0 to PHP_INT_MAX unless you specify your own range. In case you use a custom range, it generates a random number within that range, but – it gets slower.

I have bench-marked the time taken by ten thousand calls to rand() with and without specifying a range. The results show that rand($min,$max) takes about 58% extra time compared to rand().

Without any range specified, rand went significantly faster. Here are ways to achieve better, although not equal, speed of random number generation if the minimum end of your range is 0 and the maximum value is anything less than or equal to PHP_INT_MAX.

Alternatively, if your desired range has minimum value 0 and the maximum value lesser than PHP_INT_MAX, and your maximum value can be expressed as 2^n - 1 where n is a whole number representing the number of bits the resulting integer would take, an even better alternative is:

So, why -1 does not work as $max in this solution?

The answer is that -1 (despite being a 2^n - 1 integer) cannot be used as $max in our second alternative solution because rand() generates random positive integers that are always 31 bits (on 32bit platforms) or 63 bits (on 64bit platforms). So, & will never let the resultant random integer have its most significant bit (or sign bit) ON and the random number will always remain positive as with 2^31 - 1.

To bypass the limit of PHP_INT_MAX or to generate larger random numbers that fit UNSIGNED INT and BIGINT MySQL data types, read my post that explains how to generate large random numbers.

This was the toughest way to work with random numbers in languages like php 🙂 but it is always good to learn.