note 77174 deleted from function.rand by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: jfkallen at hotmail dot com 

----

In regards to mno2go's note below on randomly generated strings, I am not sure what's inefficient about this.  I like it and am using it in several modules (so thanks).  I made a few tweaks though.  There is a fence-post error in the code (a string's range is 0 to n-1).  There is also excessive calls to strlen.

<?php
    function generateCode($length=6) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
        $code = "";
        $clen = strlen($chars) - 1;  //a variable with the fixed length of chars correct for the fence post issue
        while (strlen($code) < $length) {
            $code .= $chars[mt_rand(0,$clen)];  //mt_rand's range is inclusive - this is why we need 0 to n-1
        }
        return $code;
    }
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.