Home  >  Article  >  Backend Development  >  How to generate random numbers in php? (code example)

How to generate random numbers in php? (code example)

青灯夜游
青灯夜游Original
2018-12-27 16:03:5149792browse

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.

How to generate random numbers in php? (code example)

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:

How to generate random numbers in php? (code example)

##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:


"); //在一个范围内生成随机数 $Num2 = mt_rand(20,100); //输出 print_r("mt_rand(20,100): ".$Num2); ?>

Output:

How to generate random numbers in php? (code example)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn