rand
and mt_rand
, according to the documentation (here and here), are not considered cryptographically secure (for this purpose, the use of random_int
, about which we will speak below).
So much rand
how much mt_rand
work in a similar way: if they are called without parameters, they return a number between zero and a maximum limit (for rand
, the limit is the number returned by getrandmax
, and to mt_rand
, the limit is the number returned by mt_getrandmax
).
If they are called with only one parameter, they both give one Warning ("expects Exactly 2 Parameters, 1 Given" <- tested in PHP 7.3.6) and return NULL
.
If they are called with 2 parameters (called $min
and $max
), return a number between $min
and $max
, remembering that both are included (in many languages the final value is not included, so this is a factor that usually generates many off-by-one errors).
One "interesting" detail is that if $min
is greater than $max
, rand
works, but mt_rand
no. That is to say, rand(5, 3)
returns a number between 3 and 5, but mt_rand(5, 3)
gives a Warning ("max(3) is smaller than min(5)") and returns FALSE
.
This happened in PHP 7.3.6 (version I used to test), even though the documentation said that from PHP 7.1 onwards rand
became a alias of mt_rand
. This behavior is mentioned in documentation of rand
:
Note: As of PHP 7.1.0, rand()
uses the same Random number Generator as mt_rand()
. To preserve Backwards Compatibility rand()
Allows max to be smaller than min as opposed to returning false as mt_rand()
.
In fact, in the above section we have another detail: from PHP 7.1 both use the same algorithm, which in this case is the Mersenne Twister (before that, rand
wore the Linear Congruential Generator).
Already random_int
has more differences. A documentation cites that it is a cryptographically secure function (and the trade-off is it be slower), and in addition it should always be called with 2 arguments, indicating the minimum and maximum values. Another difference to rand
and mt_rand
is that if the maximum is less than the minimum, a Error
.
This function launches a Exception
if no source of randomness appropriate. According to the documentation, this source varies according to the environment:
- in Windows, for PHP >= 7.2.0 the CNG-API, for other versions is used
CryptGenRandom
- on Linux, the syscall
getrandom(2)
, if available
- on other platforms, use
/dev/urandom
- if none of these are found, launches a
Exception
About "being cryptographically secure", see more details here and here. But basically, if you’re not dealing with encryption (for example, if you just want to change the background color of your website randomly), wouldn’t need to use random_int
.
Related: How computer randomization is generated? and What is a random seed?
– Wallace Maxters
Starting from PHP 7.1,
rand
is a alias formt_rand
. Behold.– Luiz Felipe