Random String Function

Reading Time: < 1 minuteA simple function to create a random string.

<?
function generateString ($length = 8)
{
  $string = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz";
  $i = 0;
  while ($i < $length) {
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    $string .= $char;

Reading Time: < 1 minute

A simple function to create a random string.

<?
function generateString ($length = 8)
{
  $string = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz";
  $i = 0;
  while ($i < $length) {
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    $string .= $char;
    $i++;
  }
  return $string;
}
?>

A bit more elegant:

<?
function getUniqueCode($length = 8)
{
$code = md5(uniqid(rand(), true));
if ($length != "") return substr($code, 0, $length);
else return $code;
}
?>

By Marc Olivier Meunier

Marc has spent the past few years putting oil on the fire of growth companies. He leads by example and puts a lot of emphasis on inclusion, constantly working to create a safe environment. A warm leader with a passion for memorable experiences and innovation.
Marc is available for contracting as a fractional Head of Customer Experience.
Find Marc on Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *