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

青灯夜游
Release: 2023-04-04 15:20:02
Original
49960 people have browsed it

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)
Copy after login
  • 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:

<?php  
// 生成随机数
$Num1 = rand(); 
//输出
print_r("rand(): ".$Num1); 
print_r("<br><br>"); 
//在一个范围内生成随机数
$Num2 = rand(20,100); 
//输出
print_r("rand(20,100): ".$Num2); 
?>
Copy after login

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)
Copy after login

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:

<?php  
// 生成随机数
$Num1 = mt_rand(); 
//输出
print_r("mt_rand(): ".$Num1); 
print_r("<br><br>"); 

//在一个范围内生成随机数
$Num2 = mt_rand(20,100); 
//输出
print_r("mt_rand(20,100): ".$Num2); 
?>
Copy after login
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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template