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

Random number in range [min - max] using PHP


<?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.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.


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