100

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Val
  • 17,336
  • 23
  • 95
  • 144
  • 1
    New php version has a cryptographically secure [random number generator](http://stackoverflow.com/a/31421151/1090562). – Salvador Dali Jul 15 '15 at 03:47
  • 1
    For PHP 7+ use `random_int()`, `random_bytes()`, or `openssl_random_pseudo_bytes() `. as @Salvador Dali said `rand()` do not generate cryptographically secure results. See documentation http://php.net/manual/en/function.rand.php – FrozenFire Jan 23 '16 at 08:56

7 Answers7

177
<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>
Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • i thought that min and max for rand was the number of digits to use instead of numbers :) thnx – Val Nov 13 '10 at 17:50
  • Related: if `PHP_INT_MAX < ($max-$min)`, you need to add intervals together, as described in [this answer](http://stackoverflow.com/questions/31252637/what-is-phps-mt-rand-minimum-value-and-how-to-calculate-32-bit-interger-on-32). – bishop Jul 10 '15 at 16:12
  • rand() before PHP7.1 is simply bad. It uses LCG algorithm which results with predictable output. It is also slow. Since PHP7.1 rand() is made an alias of mt_rand() therefore no longer bad. PHP7 also introduced cryptographically secure random_int(), however it should be avoided unless essential, since it's much slower than mt_rand() – xZero Dec 13 '18 at 09:17
44

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.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 2
    That's great! But until webhosts support PHP7 more globally, this is not useful for anyone building products for distribution unfortunately. So the previous answers that ALSO work on PHP7 are still best practice. – Matt Cromwell Nov 03 '16 at 18:32
  • 1
    @MattCromwell. I do not agree with you. Until hosting services support PHP7 we should use polyfill for `random_int` and `random_bytes` function - https://github.com/paragonie/random_compat. – Vladimir Posvistelik Jan 08 '17 at 19:41
  • I'm curious, is there ever a reason NOT to use `random_int `? If it gives "better" random numbers, why not use it for non-crypto reasons? – Brian Leishman Sep 21 '17 at 16:13
  • 1
    @BrianLeishman I would rather use it for everything. The only downside that I can guess: it probably relies on the source of randomness and might fail if you are out of randomness. It might be more expensive (need to check) but I doubt that this one function makes a big difference – Salvador Dali Sep 21 '17 at 17:54
  • I do know that it's slower, but it's insignificant enough to not go back and change already existing `random_int`s to `rand`s. Also, my use case is a retry algorithm, and I definitely don't want multiple failed functions clumping after sleeping because of predictable random ints – Brian Leishman Sep 21 '17 at 18:18
21

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

Matt Cromwell
  • 375
  • 2
  • 9
  • 7
    you mean faster right ? the difference is (typing==quicker vs faster==performance wise) – Val Feb 11 '14 at 11:16
  • https://english.stackexchange.com/questions/31732/what-is-the-difference-between-quicker-and-faster - actually can be both – pee2pee Jun 02 '20 at 17:55
9

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
}
vonUbisch
  • 1,384
  • 17
  • 32
5
(rand() % ($max-$min)) + $min

or

rand ( $min , $max )

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

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
5
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.

winwaed
  • 7,645
  • 6
  • 36
  • 81
0

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;
}
asi_x
  • 69
  • 5