Drill down to PHP to get the details of random Numbers and letters

  • 2020-06-07 04:05:14
  • OfStack

The first method


<?php
  $FileID=date("Ymd-His") . '-' . rand(100,999);
  //$FileID for    20100903-132121-908    Random Numbers like that 
?>

The second method

<?php
function randomkeys($length) {
    $returnStr='';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern {mt_rand ( 0, 61 )}; // generate php The random number 
    }
    return $returnStr;
}
echo randomkeys(4);
?>

The third method

<?php
//seed User-defined functions are seeded in microseconds 
function seed()
{
list($msec, $sec) = explode(' ', microtime());
return (float) $sec;
}
// Seed the random number generator with srand A function call seed The function returns the result 
srand(seed());
// Output the random number generated, the random number range is 10-100
echo rand(10,100);
?>

Isn't the top one the same as the bottom one? All are random output between 10-100 Numbers, new learning, may ask too simple ha ha

<?php
echo rand(10,100);
?>
mt_rand(10,100);

srand is the seed, which defaults to 1 if not set
rand1 is generally a fixed operation using seeds as parameters
You try it 1, no seed or set a fixed seed, run rand
Then close the browser, open it again, and run rand
You'll see that the number 1 is the same thing
Start with the rand() function, rand([int min], [int max])
This function selects a random number between min and max. If the maximum and minimum range of random number is not specified, this function will automatically select a random number from 0 to RAND_MAX.
However, if you only use the rand() function, the random number will be very messy, and it is better to use the srand() function to configure the new random number seed before each random number.
Explain the following usage:
srand((double)microtime()*1000000);
$rand_number= rand();
microtime() returns two values: the current millisecond and the timestamp. To extract the random number, we can only take one random number from the millisecond. (double)microtime() returns only the current ms value.
microtime() is the number of milliseconds in seconds, so the values are decimals, multiplied by 1000000 to convert them to integers

Their workflow is as follows:
(1): First, provide srand() with a "seed"; Is a value of type unsigned_int.
(2):_ Then, call rand(), which returns a random number between _0 and 32767 based on the value provided to srand()
(3): Call rand() several times as needed to get new random Numbers.
(4): Whenever a new "seed" can be provided to srand() to further "randomize" rand()
Output the result.


Related articles: