Random String Function

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;

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 a hyper growth ad tech company. At Smartly.io he was in charge of scaling the support and its culture. At Eficode he is now leading an engineering team and running operations. He leads by example and puts a lot of emphasis on diversity and inclusion, constantly working to create a safe environment. A warm leader with a passion for memorable experiences and innovation.
Find Marc on Linkedin

Leave a Reply

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