在范围内的随机数[最小-最大]使用 PHP

有没有办法根据最小值和最大值生成一个随机数?

例如,如果 min 是1,max 是20,它应该生成1到20之间的任何数字,包括1到20?

143730 次浏览
<?php
$min=1;
$max=20;
echo rand($min,$max);
?>
(rand() % ($max-$min)) + $min

or

rand ( $min , $max )

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

rand(1,20)

Docs for PHP's rand function are here:

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

Use the srand() function to set the random number generator's seed value.

A quicker faster version would use mt_rand:

$min=1;
$max=20;
echo mt_rand($min,$max);

Source: 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().

Try This one. It will generate id according to your wish.

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

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

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
}