简体   繁体   English

使用 PHP 的 [min - max] 范围内的随机数

[英]Random number in range [min - max] using PHP

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?例如,如果 min 为 1,max 为 20,它应该生成 1 到 20 之间的任何数字,包括 1 和 20?

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

In a new PHP7 there 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.这基本上使以前的答案过时了。

A quicker faster 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.注意:您的服务器需要启用 Math PHP 模块才能正常工作。 If it doesn't, bug your host to enable it, or you have to use the normal (and slower) rand().如果没有,请让您的主机启用它,或者您必须使用正常(且速度较慢)的 rand()。

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
}
(rand() % ($max-$min)) + $min

or或者

rand ( $min , $max )

http://php.net/manual/en/function.rand.php http://php.net/manual/en/function.rand.php

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()函数设置随机数生成器的种子值。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM