Random String Generation in PHP

By Keith Connolly on October 26, 2010

Get Reading

So here's a nice little function you can use as you like to generate a string of any length with any sequence of characters. A quick breakdown: the function gets the length of the $chars string and uses that to determine the 'index in a width-wise mannor' of character that'll be used for each random digit or character. We then iterate through a random member of the string (using the string index and the rand function) the number of times we need in order to reach the desired length. Please, note that we are using a negative-wise 'for loop' which runs faster.

function rand_string($length = 36, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890') {
  $width = (strlen($chars)-1);
  for ($i = $length; $i != 0; $i--) {
    $r = $chars{rand(0, $width)};
    $string .= $r;
  return $string;

I hope you find this useful!

Get in touch

I really like hearing from those who read my content, engauge with me via the comments on each post are by one of the many contact methods below.

Keith Connolly
Queen Creek, Arizona 85142
P: (480) 231-9285