Php random number php mt_srand play a better random number generator seed
Mt_srand
(PHP 3> = 3.0.6, PHP 4, PHP 5)
Mt_srand -- play a better random number generator seed
Description
Void mt_srand (int seed)
Seed is used to seeding the random number generator. Starting from PHP 4.2.0, the seed parameter becomes optional. when this item is null, it is set to the number at any time.
Example 1. mt_srand ()
Code
// Seed with microseconds
Function make_seed ()
{
List ($ usec, $ sec) = explode ('', microtime ());
Return (float) $ sec + (float) $ usec * 100000 );
}
Mt_srand (make_seed ());
$ Randval = mt_rand ();
?>
Note: As of PHP 4.2.0, the srand () or mt_srand () function is no longer required for seeding the random number generator. it is now automatically completed.
See mt_rand (), mt_getrandmax () and srand ().
PHP mt_rand () function
Definition and usage
Mt_rand () returns a random integer using the Mersenne Twister algorithm.
Syntax
mt_rand ( min , max )
Description
If the optional parameters min and max are not provided, mt_rand () returns a pseudo-random number between 0 and RAND_MAX. For example, if you want a random number between 5 and 15 (including 5 and 15), use mt_rand (5, 15 ).
Many old libc random number generators have some uncertain and unknown features and are very slow. The rand () function of PHP uses the libc random number generator by default. The mt_rand () function is informal to replace it. This function uses known features in Mersenne Twister as a random number generator, which can generate random values at an average speed four times faster than the rand () provided by libc.
Tips and comments
Note: Since PHP 4.2.0, the random number generator is no longer needed to be planted using the srand () or mt_srand () function, which is now automatically completed.
Note: In versions earlier than 3.0.7, max indicates range. In these versions, we need to obtain a random number from 5 to 15, which is the same as the preceding example. The short example is mt_rand (5, 11 ).
Example
In this example, we will return some random numbers:
The output is similar:
3150906288 513289678 35
Note: the random integer given by the above function cannot be any character other than the number. if you want to generate other characters, you need to customize the method as follows:
Code
/*
* $ Length: the length of the random number string
* $ Type: type of the random number generated
**/
Function random ($ length, $ type = ""){
$ Chars =! $ Type? "ABC defghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz": "0123456789 abcdef ";
$ Max = strlen ($ chars)-1;
Mt_srand (double) microtime () * 1000000 );
For ($ I = 0; $ I <$ length; $ I ++ ){
$ String. = $ chars [mt_rand (0, $ max)];
}
Return $ string;
}
$ Var = random (32, 'hahaha ');
Echo ($ var );
?>
Output:
Fe61e294e5f46437cb3a92b92643ead6