Advertisement
ridjis

rnd

Jul 10th, 2014
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.19 KB | None | 0 0
  1. A nice function to generate a random string, using any character:
  2.  
  3. <?php
  4. function generateRandStr($length){
  5.       $randstr = "";
  6.       for($i=0; $i<$length; $i++){
  7.          $randnum = mt_rand(0,61);
  8.          if($randnum < 10){
  9.             $randstr .= chr($randnum+48);
  10.          }else if($randnum < 36){
  11.             $randstr .= chr($randnum+55);
  12.          }else{
  13.             $randstr .= chr($randnum+61);
  14.          }
  15.       }
  16.       return $randstr;
  17.    }
  18. ?>
  19.  
  20. Simply use:
  21. generateRandStr(10);
  22.  
  23. Sample output: $%29zon(4f
  24.  
  25. <?php
  26.  
  27. $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
  28.  
  29. $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
  30.  
  31. ?>
  32.  
  33. I thought this function (random color) might be of use to someone [to create and return a random hex for HTML colors]:
  34.  
  35. <?php
  36. function get_random_color()
  37. {
  38.     for ($i = 0; $i<6; $i++)
  39.     {
  40.         $c .=  dechex(rand(0,15));
  41.     }
  42.     return "#$c";
  43. }
  44. ?>
  45.  
  46. http://www.sitepoint.com/php-random-number-generator/
  47. http://php.net/manual/en/function.rand.php
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement