note 27588 added to function.mt-srand
| From: | mattb at columbia dot edu | Date: | Thu, 12 Dec 2002 06:54:26 +0000 |
| Subject: | note 27588 added to function.mt-srand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-40782@lists.php.net to get a copy of this message | ||
This is effectively the same thing, but it uses a more efficient bit mask instead of a substring.
Here's the verbose version:
function mkseed()
{
$hash = md5(microtime());
$loWord = substr($hash, -8);
$seed = hexdec($loWord);
$seed &= 0x7fffffff;
return $seed;
}
Or, if you're a real hacker, this is a more concise version:
function mkseed()
{
return hexdec(substr(md5(microtime()), -8)) & 0x7fffffff;
}
Note, the range on the md5 sum is really arbitrary. You could use whatever portion you like, just so
long as it's 32 bits.
Now just call mt_srand() (once) as follows:
mt_srand(mkseed());
Of course, unless you wanted the mkseed() function for something else, you could skip all that jive
and just do this somewhere in a global include file:
<?php
/*
Global include file. Make sure this gets included before using
mt_rand().
*/
if (!isset($_MyApp_MtSrand)
|| !$_MyApp_MtSrand)
{
$_MyApp_MtSrand = true;
mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
}
?>
--
http://www.php.net/manual/en/function.mt-srand.php
http://master.php.net/manage/user-notes.php?action=edit+27588
http://master.php.net/manage/user-notes.php?action=delete+27588
http://master.php.net/manage/user-notes.php?action=reject+27588