Example Analysis of PHP Random Number Generation Method

Source: Internet
Author: User
This article mainly introduces the PHP method for generating random numbers. It compares two different methods for generating random numbers and summarizes the techniques related to random numbers. For more information, see

This article mainly introduces the PHP method for generating random numbers. It compares two different methods for generating random numbers and summarizes the techniques related to random numbers. For more information, see

Generally, when we want to generate a random string, we always create a character pool first, and then generate a php random number using a loop and mt_rand () or rand, randomly select characters from the character pool, and finally piece together the required length.

The Code is as follows:

Function randomkeys ($ length)
{
$ Pattern = '1234567890abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./& l
T;> ?; #:@~ [] {}-_ = +) (* & ^ % ___ FCKpd __0 pound ;"! '; // Character pool
For ($ I = 0; $ I <$ length; $ I ++)
{
$ Key. = $ pattern {mt_rand ()}; // generate a php Random Number
}
Return $ key;
}
Echo randomkeys (8 );

This php random function can generate XC * = z ~ A string like 7L is random enough! Now we will introduce another method to generate random numbers using PHP: Use the chr () function to save the steps to create a character pool.

The Code is as follows:

Function randomkeys ($ length)
{
$ Output = '';
For ($ a = 0; $ a <$ length; $ a ++ ){
$ Output. = chr (mt_rand (33,126); // generate a php Random Number
}
Return $ output;
}
Echo randomkeys (8 );

In the second php random function, use mt_rand () to generate a php random number between 33 and 126, and then convert it into characters using the chr () function. View the ascii code table and you will find that 33 to 126 represents all the characters in the character pool of the first function. The second function has the same functionality as the first function, and is more concise.

I hope this article will help you with php programming.

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.