What is the method for generating random numbers in PHP

Source: Internet
Author: User
This time for everyone to bring PHP to generate random number of methods, PHP generated random number of considerations, the following is the actual case, together to see.

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)

function Make_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 ', '! ',  ' @ ', ' # ', ' $ ', '% ', ' ^ ', ' & ', ' * ', ' (', ') ', '-', ' _ ', '  [', '] ', ' {', '} ', ' < ', ' > ', ' ~ ', ' ', ' + ', ' = ', ', ', '. ', '; ', ': ', '  /', '? ', ' | ';  $length number of element key names are randomly taken in the $chars  $keys = Array_rand ($chars, $length);  $password = ";  for ($i = 0; $i < $length; $i + +)  {   //to concatenate $length array elements into string   $password. = $chars [$keys [$i]];  }  return $password; }

The third Kind takes the time stamp

function Get_password ($length = 8) {  $STR = substr (MD5 (Time ()), 0, $length),//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; }

Start to create verification code (directly generated with the function, 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 =0; $i <5; $i + +) {  echo lcg_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 */function randfloat ($min =0, $max =1) {return $ Min + mt_rand ()/mt_getrandmax () * ($max-$min);} Get Microtimefunction get_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 Runtime printf ("Run time%f ms\r\n", ($endtime-$starttime) *1000);? >

Output: Run time 266.893148 ms

Run time of Lcg_value () 100,000 times

<?php//gets Microtimefunction get_microtime () {list ($usec, $sec) = Explode (', microtime ()), return (float) $usec + (Floa t) $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 Runtime printf ("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 */function randfloat ($min =0, $max =1) {return $ Min + mt_rand ()/mt_getrandmax () * ($max-$min);} Header (' content-type:image/png '); $im = Imagecreatetruecolor (at 255); $color 1 = imagecolorallocate ($im, 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 (+), $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 = l Cg_value ();  if (Round ($rand, 2) >=0.5) {   imagesetpixel ($im, $x, $y, $color 1);  } else{   imagesetpixel ($im, $x, $y, $color 2);}}  Imagepng ($im); Imagedestroy ($im);? >

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Anaconda's Novice use Daquan

How to install a third-party library in win Anaconda

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.