Random Character Generation in PHP and JavaScript

I wrote this function in response to someone else’s attempt on a forum I was asked to join. It basically generates a string of random letters and numbers with the letters being in both upper and lower case. It is easy to edit it to only use upper or lower case letters or even add symbols as well. I initially wrote it in PHP and then rewrote it in JavaScript as well.

function randomString($strLen = 32)
  // Create our character arrays
  $chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
  // Just to make the output even more random
  // Create a holder for our string
  $randStr = '';
  // Now loop through the desired number of characters for our string
  for($i=0; $i< $strLen; $i++)
    $randStr .= $chrs[mt_rand(0, (count($chrs) - 1))];
  return $randStr;

Using it is simply a case of calling it and specifying how long to make the string otherwise it uses the default length of 32 characters.

echo randomString(12);

To also make it use symbols you just change the array_merge to

// If we want letters, numbers and symbols
$chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9), array('!','£','$','%','^','&','*','(',')','-','=','+','@','#','~','?'));

Now for the JavaScript version. JavaScript has neither a range() function nor an easy way to shuffle an array so the code here is a little longer.

function randomString(len) {
  // Just an array of the characters we want in our random string
  var chrs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
              'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
  // Check that a length has been supplied and if not default to 32
  len = (isNaN(len)) ? 32 : len;
  // The following section shuffles the array just to further randomise the output
  var tmp, current, top = chrs.length; 
      current = Math.floor(Math.random() * (top + 1)); 
      tmp = chrs[current]; 
      chrs[current] = chrs[top]; 
      chrs[top] = tmp; 
  // Just a holder for our random string
  var randomStr = '';
  // Loop through the required number of characters grabbing one at random from the array each time
    randomStr = randomStr + chrs[Math.floor(Math.random()*chrs.length)];
  // Return our random string
  return randomStr;

Leave a Reply

Post Popularity Graphing by Knowledge Ring