Random string generator


/ Published in: PHP
Save to your folder(s)

Testing a couple different ways to create a random string 3 characters long [a-zA-Z0-9]. Turns out mod is pretty quick!


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. header('Content-Type: text/plain');
  4.  
  5. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  6. $chars_strlen = strlen($chars); //turns out this is fairly expensive; make sure to only do it once
  7.  
  8. $timer = microtime(true);
  9. for ($i=0; $i<1000000; $i++) {
  10. $uid = $chars[rand(0, $chars_strlen-1)] . $chars[rand(0, $chars_strlen-1)] . $chars[rand(0, $chars_strlen-1)];
  11. # echo $uid . "\n";
  12. }
  13. echo microtime(true) - $timer . ' seconds using rand(0, strlen()-1)' . "\n"; # 1.6855049133301 seconds
  14.  
  15.  
  16. echo "\n" . str_repeat('-', 80) . "\n\n";
  17.  
  18.  
  19. $timer = microtime(true);
  20. for ($i=0; $i<1000000; $i++) {
  21. $uid = substr(str_shuffle($chars), 0, 3);
  22. # echo $uid . "\n";
  23. }
  24. echo microtime(true) - $timer . ' seconds using str_shuffle()' . "\n"; # 1.9944579601288 seconds
  25.  
  26.  
  27. echo "\n" . str_repeat('-', 80) . "\n\n";
  28.  
  29.  
  30. $timer = microtime(true);
  31. for ($i=0; $i<1000000; $i++) {
  32. $uid = $chars[rand() % $chars_strlen] . $chars[rand() % $chars_strlen] . $chars[rand() % $chars_strlen];
  33. # echo $uid . "\n";
  34. }
  35. echo microtime(true) - $timer . ' seconds using mod strlen()' . "\n"; # 1.0942420959473 seconds

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.