In this tutorial, we are going to show you how to generate a random number using PHP.
We will also explain why you should use the random_int function instead of rand and mt_rand.
Let’s take a look at a simple example:
//The minimum / lowest number. $min = 0; //The max / highest number. $max = 10; //Generate a random number using the rand function. $number = random_int($min, $max); //Print the result echo $number;
In the code above, we use PHP’s random_int function to generate a random number between 0 and 10.
If we want a number between 1 and 10, then we can simply change our $min variable to 1, as $min is the lowest value that the rand function should return.
If we want an integer between 1 and 100, then we can change $min to 1 and $max to 100.
Using the random_int function is a much better solution than using other “pseudo-random” functions such as rand and mt_rand.
The problem with rand and mt_rand is that they are not cryptographically secure. This means that you cannot use them for anything security-related.
In simple terms, they’re not really random. As a result, a third party might be able to predict which numbers they are going to generate.
If you are using an older version of PHP, then you will probably encounter the following fatal error:
“Fatal error: Call to undefined function random_int()”
This is because the random_int function was only introduced in PHP 7.
If you are still using PHP 5, then you can download the random_compat library from Github. This library will basically create the function for PHP 5.x.
Related: Generate a random token with PHP.