PHP: Random string with numbers and letters

I thought that some of you might find it useful to learn how to generate a random string or a random number with PHP. I wrote a quick function to use PHP to generate random. See it below :

function genRandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

There is an easier way to do this with a single line of code but you won’t have as much control over the characters that you want to include/exclude from the random PHP string. Here it is:

$string = substr(md5(microtime()), rand(0,99), 10);
  • http://tribulant.com/ Antonie Potgieter

    Thanks for your comment and tip, I’m sure it will be useful to readers here.