Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PHP Random String

Name: Fag 2010-09-03 0:02

Alright, so I can't for the life of me figure out why this is happening. Sometimes this is returning 11 characters, other times it is returning 12. Any ideas? I'd like it to consistently be 12 characters.

Also, I'm a fag and don't know how to make the code appear in monospace, and I'm not going to be a dumbass trying to make html/bbcode work here, so here is the unformatted code.

function RandomString() {
    $length = 12;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $real_string_legnth = strlen($characters) - 1;
    $string = "";

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

    return $string;
}

Name: Anonymous 2010-09-03 0:22

The second parameter to mt_rand should be strlen($characters)-1. The way it is now, when mt_rand returns 36, no character is appended to $string, making the result shorter than you expect. It could be even shorter if mt_rand generates 36 a bunch of times. I don't even know PHP.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List