Generating (pseudo)random alpha-numeric strings


Question

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

1
82
10/5/2008 6:18:15 AM

Accepted Answer

First make a string with all your possible characters:

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

You could also use range() to do this more quickly.

Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:

 $string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }

$random_string_length is the length of the random string.

163
8/1/2016 11:30:50 AM

I like this function for the job

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon