The mt_rand()
function uses the Mersenne Twister algorithm to
generates random numbers.
PHP mt_rand() Function has the following syntax.
int mt_rand ( [int min, int max] )
Parameter | Is Required | Description |
---|---|---|
min | Optional. | Lowest number to be returned. Default is 0 |
max | Optional. | Highest number to be returned. Default is mt_getrandmax() |
Without parameters, mt_rand()
will return a number between 0 and mt_getrandmax()
.
If you supply it with two parameters, mt_getrandmax() will use those as the upper and lower limits for the random number. The limits are inclusive: if you specify 1 and 3, your random number could be 1, 2, or 3.
Item | Value |
---|---|
Return Value | A random integer between min (or 0) and max (or mt_getrandmax() inclusive). Returns FALSE if max < min |
Return Type | Integer |
Generate random number in a range.
<?PHP
$mtrand = mt_rand();
print $mtrand;
print "\n";
$mtrandrange = mt_rand(1,100);
print $mtrandrange;
?>
The code above generates the following result.
The following code generates random password.
<?php//from w ww . j av a 2 s . c o m
function GeneratePassword($min = 5, $max = 8) {
$ValidChars = "abcdefghijklmnopqrstuvwxyz123456789";
$max_char = strlen($ValidChars) - 1;
$length = mt_rand($min, $max);
$password = "";
for ($i = 0; $i < $length; $i++) {
$password .= $ValidChars[mt_rand(0, $max_char)];
}
return $password;
}
echo "New Password = " . GeneratePassword() . "\n";
echo "New Password = " . GeneratePassword(4, 10) . "\n";
?>
The code above generates the following result.