Home>Article>Backend Development> How to generate random numbers in php? (code example)
In PHP, you can use the built-in functions rand() and mt_rand() to randomly generate a number. Below we will introduce how these two built-in functions of PHP generate random numbers. We hope it will be helpful to everyone.
rand() function
rand() function can be specified to generate random numbers within a certain range integer and returns this random number.
Basic syntax:
rand(min,max)
min
: Specifies the minimum value that will be returned.
#max
: Specifies the maximum value that will be returned.
Note:
If min and max are specified in the rand() function, random numbers will be generated in the range of [min, max]; if not specified min and max, the random number will be generated in the range [0, getrandmax()].
The return value of the getrandmax() function is: the maximum upper limit (maximum possible value) that the rand() function can return.
Example:
"); //在一个范围内生成随机数 $Num2 = rand(20,100); //输出 print_r("rand(20,100): ".$Num2); ?>
Output result:
##mt_rand() function
The mt_rand() function is based on the Mersenne Twister algorithm and can quickly generate a random integer. Basic syntax:mt_rand($min,$max)Parameter description: $min: Optional parameter, specifies the minimum number to be returned, the default value is 0. $max: optional parameter. It specifies the maximum number to return. When $min and $max exist, return a random integer between [min, max]; if $min and $max do not exist, return a random integer between [0, maximum possible value] . Example:
Output:
"); //在一个范围内生成随机数 $Num2 = mt_rand(20,100); //输出 print_r("mt_rand(20,100): ".$Num2); ?>
Explanation:mt_rand() function can generate better random values; and it is the same as rand( ) function, it generates faster.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.The above is the detailed content of How to generate random numbers in php? (code example). For more information, please follow other related articles on the PHP Chinese website!