note 77174 added to function.rand
| From: | jfkallen at hotmail dot com | Date: | Sat, 18 Aug 2007 02:21:54 +0000 |
| Subject: | note 77174 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129570@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 71.88.251.22
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/77174
Del: integrated -- https://master.php.net/note/delete/77174/integrated
Del: useless -- https://master.php.net/note/delete/77174/useless
Del: bad code -- https://master.php.net/note/delete/77174/bad+code
Del: spam -- https://master.php.net/note/delete/77174/spam
Del: non-english -- https://master.php.net/note/delete/77174/non-english
Del: in docs -- https://master.php.net/note/delete/77174/in+docs
Del: other reasons-- https://master.php.net/note/delete/77174
Reject -- https://master.php.net/note/reject/77174
Search -- https://master.php.net/manage/user-notes.php