Posted By

Sverri on 05/26/11


Tagged

random


Versions (?)

Random string


 / Published in: PHP
 

A function that returns a random alphanumeric string.

  1. function random_string($length, $max=FALSE)
  2. {
  3. if (is_int($max) && $max > $length)
  4. {
  5. $length = mt_rand($length, $max);
  6. }
  7. $output = '';
  8.  
  9. for ($i=0; $i<$length; $i++)
  10. {
  11. $which = mt_rand(0,2);
  12.  
  13. if ($which === 0)
  14. {
  15. $output .= mt_rand(0,9);
  16. }
  17. elseif ($which === 1)
  18. {
  19. $output .= chr(mt_rand(65,90));
  20. }
  21. else
  22. {
  23. $output .= chr(mt_rand(97,122));
  24. }
  25. }
  26. return $output;
  27. }

Report this snippet  

You need to login to post a comment.