Home  >  Article  >  Backend Development  >  Function to generate random numbers using PHP

Function to generate random numbers using PHP

WBOY
WBOYOriginal
2016-07-25 09:02:44993browse
  1. function randomkeys($length)
  2. {
  3. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz
  4. ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&l
  5. t;>?;#:@~[]{ }-_=+) (*&^%___FCKpd___0pound;”!'; //Character pool
  6. for($i=0;$i<$length;$i++)
  7. {
  8. $key .= $pattern{mt_rand(0,35)}; //Generate PHP random numbers
  9. }
  10. return $key;
  11. }
  12. echo randomkeys(8); This PHP random function can generate strings like Random number method: Use the chr() function to save the step of creating a character pool. function randomkeys($length)
  13. {
  14. $output=”;
  15. for ($a = 0; $a < $length; $a++ ) {
  16. $output .= chr(mt_rand(33, 126)); //Generate php random numbers
  17. }
  18. return $output;
  19. }
  20. echo randomkeys(8);
  21. ?>
Copy code
Note: In the second PHP random function, first use mt_rand() to generate a PHP random number between 33 and 126, and then use the chr() function to convert it into characters. Looking at the ascii code table, you will find that 33 to 126 represent all the characters in the character pool in the first function. The second function has the same functionality as the first function, but is more concise.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:"Oh my god."Next article:"Oh my god."