使用 PHP 在 [min - max] 范围内的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4173867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random number in range [min - max] using PHP
提问by Val
Is there a way to generate a random number based on a min and max?
有没有办法根据最小值和最大值生成随机数?
For example, if min was 1 and max 20 it should generate any number between 1 and 20, including 1 and 20?
例如,如果最小值为 1,最大值为 20,它应该生成 1 到 20 之间的任何数字,包括 1 和 20?
回答by Prisoner
<?php
$min=1;
$max=20;
echo rand($min,$max);
?>
回答by Salvador Dali
In a new PHP7there is a finally a support for a cryptographically secure pseudo-random integers.
在新的PHP7 中,终于支持加密安全的伪随机整数。
int random_int ( int $min , int $max )
random_int — Generates cryptographically secure pseudo-random integers
random_int — 生成加密安全的伪随机整数
which basically makes previous answers obsolete.
这基本上使以前的答案过时了。
回答by Matt Cromwell
A quickerfaster version would use mt_rand:
一个更快的速度更快的版本将使用mt_rand:
$min=1;
$max=20;
echo mt_rand($min,$max);
Source: http://www.php.net/manual/en/function.mt-rand.php.
来源:http: //www.php.net/manual/en/function.mt-rand.php。
NOTE:Your server needs to have the Math PHP module enabled for this to work. If it doesn't, bug your host to enable it, or you have to use the normal (and slower) rand().
注意:您的服务器需要启用 Math PHP 模块才能正常工作。如果没有,请调试您的主机以启用它,或者您必须使用正常的(和较慢的)rand()。
回答by pinkfloydx33
回答by vonUbisch
I have bundled the answers here and made it version independent;
我在这里捆绑了答案并使其独立于版本;
function generateRandom($min = 1, $max = 20) {
if (function_exists('random_int')):
return random_int($min, $max); // more secure
elseif (function_exists('mt_rand')):
return mt_rand($min, $max); // faster
endif;
return rand($min, $max); // old
}
回答by winwaed
rand(1,20)
Docs for PHP's rand function are here:
PHP rand 函数的文档在这里:
http://php.net/manual/en/function.rand.php
http://php.net/manual/en/function.rand.php
Use the srand()
function to set the random number generator's seed value.
使用该srand()
函数设置随机数生成器的种子值。
回答by asi_x
Try This one. It will generate id according to your wish.
试试这个。它将根据您的意愿生成 id。
function id()
{
// add limit
$id_length = 20;
// add any character / digit
$alfa = "abcdefghijklmnopqrstuvwxyz1234567890";
$token = "";
for($i = 1; $i < $id_length; $i ++) {
// generate randomly within given character/digits
@$token .= $alfa[rand(1, strlen($alfa))];
}
return $token;
}