Several methods of generating random numbers in PHP

Source: Internet
Author: User
Tags explode md5 md5 encryption rand

The first method uses Mt_rand ()
function Getrandstr ($length) {$str = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '; $len =strlen ( $STR)-1; $randstr = ", for ($i =0; $i < $length; $i + +) {$num =mt_rand (0, $len); $randstr. = $str [$num];} return $RANDSTR;} $number =getrandstr (6); Echo $number;

 

The second method (fastest)
functionMake_password ($length= 8 ){    //password character Set, you can add any character you need    $chars=Array(' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' W ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', '! ', ' @ ', ' # ', ' $ ', '% ', ' ^ ', ' & ', ' * ', ' (', ' ', '-', ' _ ', ' [', '] ', ' {', '} ', ' < ', ' > ', ' ~ ', ' ', ' ' + ', ' = ', ', ', ', ', ', ', ', '/', '? ', |); //randomly take $length number of element key names in the $chars    $keys=Array_rand($chars,$length); $password= ' ';  for($i= 0;$i<$length;$i++)    {        //concatenate $length array elements into a string        $password.=$chars[$keys[$i]]; }    return $password;}

The third Kind takes the time stamp
function $length = 8 ) {    $strsubstr(Time$length) (MD5);   MD5 encryption, time () the current timestamp    return$str;}

Fourth type of scrambled string
function Getrandstr () {$str= ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 '; $randStr Str_shuffle ($str); // Scrambled String $rands substr ($randStr, 0,6); // substr (string,start,length); Returns part of a string return $rands ;}

5//start to create verification code (directly with function generation, relatively convenient and quick)

$code Rand (10000, 99999);
PHP Mt_rand generate 0~1 random decimals effect comparison

Lcg_value description

float Lcg_value (void)
Lcg_value () returns a pseudo-random number with a range of (0, 1). This function combines two co-generators with a period of 2^31-85 and 2^31-249. The period of this function is equal to the product of the two primes.

Returns: the pseudo-random number of the range (0, 1).

<? PHP  for ($i$i$i+ +)    {echolcg_value().  Php_eol;}? >


Output:

0.11516515851995
0.064684551575297
0.68275174031189
0.55730746529099
0.70215008878091

Comparison of two generation 0~1 random decimal methods


1. Execution Time Comparison

Executes 100,000 times based on the Mt_rand () and Mt_getrandmax () algorithm run time

<?PHP/** * Generate 0~1 random decimals * @param int $min * @param int $max * @return Float*/functionRandfloat ($min=0,$max=1){    return $min+Mt_rand()/Mt_getrandmax() * ($max-$min);} //Get MicrotimefunctionGet_microtime () {List($usec,$sec) =Explode(‘ ‘,Microtime()); return(float)$usec+ (float)$sec;} //Record start time$starttime=get_microtime ();//execute 100,000 times to get random decimals for($i= 0;$i<100000;$i++) {randfloat ();}//Record End Time$endtime=get_microtime ();//Output Run timeprintf("Run time%f ms\r\n", ($endtime-$starttime) *1000);?>

Output: Run time 266.893148 ms

Run time of Lcg_value () 100,000 times

<?PHP//Get MicrotimefunctionGet_microtime () {List($usec,$sec) =Explode(‘ ‘,Microtime()); return(float)$usec+ (float)$sec;} //Record start time$starttime=Get_microtime (); //execute 100,000 times to get random decimals for($i= 0;$i<100000;$i++){    Lcg_value();} //Record End Time$endtime=Get_microtime (); //Output Run timeprintf("Run time%f ms\r\n", ($endtime-$starttime) *1000);?>

Output: Run time 86.178064 ms


Execution time comparison, because Lcg_value () is directly php native method, while Mt_rand () and Mt_getrandmax () need to call two methods, and need to calculate, so Lcg_value () execution time is about 3 times times faster.


2. Comparison of random effects

Random effects based on the Mt_rand () and Mt_getrandmax () algorithms

<?PHP/** * Generate 0~1 random decimals * @param int $min * @param int $max * @return Float*/functionRandfloat ($min=0,$max=1){    return $min+Mt_rand()/Mt_getrandmax() * ($max-$min);} Header(' Content-type:image/png ');$im= Imagecreatetruecolor (512, 512);$color 1= Imagecolorallocate ($im, 255, 255, 255);$color 2= Imagecolorallocate ($im, 0, 0, 0); for($y= 0;$y<512;$y++){     for($x= 0;$x<512;$x++){        $rand=randfloat (); if(round($rand, 2) >=0.5) {Imagesetpixel ($im,$x,$y,$color 1); }Else{Imagesetpixel ($im,$x,$y,$color 2); }}}imagepng ($im); Imagedestroy ($im);?>

Random effects of Lcg_value ()

<?PHPHeader(' Content-type:image/png ');$im= Imagecreatetruecolor (512, 512);$color 1= Imagecolorallocate ($im, 255, 255, 255);$color 2= Imagecolorallocate ($im, 0, 0, 0); for($y= 0;$y<512;$y++){     for($x= 0;$x<512;$x++){        $rand=Lcg_value(); if(round($rand, 2) >=0.5) {Imagesetpixel ($im,$x,$y,$color 1); }Else{Imagesetpixel ($im,$x,$y,$color 2); }}}imagepng ($im); Imagedestroy ($im);?>

Several methods of generating random numbers in PHP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.