PHP mt_rand() Function

In this chapter you will learn:

  1. Definition for PHP mt_rand() Function
  2. Syntax for PHP mt_rand() Function
  3. Parameter for PHP mt_rand() Function
  4. Return for PHP mt_rand() Function
  5. Example - Generate random number in a range
  6. Example - generate random password

Definition

The mt_rand() function uses the Mersenne Twister algorithm to generates random numbers.

Syntax

PHP mt_rand() Function has the following syntax.

int mt_rand ( [int min, int max] )

Parameter

ParameterIs Required Description
minOptional. Lowest number to be returned. Default is 0
maxOptional. 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.

Return

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

Example 1

Generate random number in a range.


<?PHP//java2 s  . c  om
$mtrand = mt_rand(); 
print $mtrand;
print "\n";
$mtrandrange = mt_rand(1,100); 
print $mtrandrange;
?>

The code above generates the following result.

Example 2

The following code generates random password.


<?php/*from   j ava2  s.  c  om*/

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.

Next chapter...

What you will learn in the next chapter:

  1. Definition for PHP mt_srand() Function
  2. Syntax for PHP mt_srand() Function
  3. Parameter for PHP mt_srand() Function
  4. Return for PHP mt_srand() Function
  5. Example - seed a random value