★ wanayoo — archive 1999 http://fr.php.net/manual/en/function.mt-rand.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<mt_getrandmaxmt_srand>
view the version of this page
Last updated: Sun, 12 Sep 2004

mt_rand

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

mt_rand -- Generate a better random value

Description

int mt_rand ( [int min, int max])

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15).

Example 1. mt_rand() example

<?php
echo mt_rand() . "\n";
echo
mt_rand() . "\n";

echo
mt_rand(5, 15);
?>

The above example will output something similar to:

1604716014
1478613278
6

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

Note: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short example should be mt_rand (5, 11) to get a random number between 5 and 15.

See also: mt_srand(), mt_getrandmax(), and rand().



add a note add a note User Contributed Notes
mt_rand
russ at garrett dot co dot uk
09-Sep-2004 10:50
That's *up to* four times faster. Depending on how rand() is implemented in your libc. The point is that mt_rand() has known performance characteristics, wheras rand() doesn't because it varies from system to system.
Julien CROUZET jucrouzet_at_cpan.org
08-Sep-2004 01:08
mt_rand is a better random method, 
BUT
mt_rand() is NOT four time faster than rand()

$> time echo "<?php  \$i = 1000000; while(\$i--) { rand(0,10); } ?>" | php
php  1.68s user 0.01s system 99% cpu 1.693 total

$> time echo "<?php  \$i = 1000000; while(\$i--) { mt_rand(0,10); } ?>" | php
php  1.69s user 0.02s system 100% cpu 1.708 total

time echo "<?php  \$i = 1000000; while(\$i--) { rand(0,100000); } ?>"
php  1.71s user 0.00s system 99% cpu 1.713 total

time echo "<?php  \$i = 1000000; while(\$i--) { mt_rand(0,100000); } ?>" | php
php  1.72s user 0.02s system 100% cpu 1.726 total
timr at onlinehome dot de
13-Aug-2004 01:24
The correct address of the inventor's FAQ is (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/efaq.html). They state that Mersenne Twister may be used for cryptography if you do some post-processing:

"Mersenne Twister is not cryptographically secure. (MT is based on a linear recursion. Any pseudorandom number sequence generated by a linear recursion is insecure, since from sufficiently long subsequence of the outputs, one can predict the rest of the outputs.)

To make it secure, you need to use some Secure Hashing Algorithm with MT. For example, you may gather every eight words of outputs, and compress them into one word (thus the length of the output sequence is 1/8 of the original one)."
charles (at) storagereview (dot) com
19-Jun-2004 08:34
Note that the MT random number generator is not recommended for use in encryption.
See http://www.math.keio.ac.jp/~matumoto/efaq.html
mina86 at tlen dot pl
09-Apr-2004 03:23
I've written simple library with functions generating random strings which supports /dev/urandom special device. It's not yet tested very well but should work ;) CVS entry's available here: http://cvs.projektcode.org/view.cgi/miki/include/random.inc.php (if it's no longer there and you really need it email me (use descriptive subject and no attachemnts so you're message won't be treated as a spam :P ))
11-Feb-2004 02:27
Here is a example of a very small, compact, quite random-random string generator. It will make a string with uppercase & lowercase letters, with numbers. You simply need to set $len in the for() structure, and then the string will be in $r.  It has been designed for size, while it's still quite fast.  Mind the wrapping, it should be 1 line.

<?php
for($len=8,$r='';strlen($r)<$len;$r.=chr(!mt_rand(0,2)?
mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand
(97,122))));
?>

Armond Carroll
tmx at ntlworld dot com
06-Dec-2003 10:26
When using this function, it doesn't matter which order the numbers go in.

     mt_rand(16,5)

works just as well as

     mt_rand(5,16)

Which can be useful if you are pulling values from a database, that could be negative or positive.

     mtrand(0,$anyinteger)

Hope this helps someone
daeken_9999 at yahoo dot com
08-Jul-2003 11:44
This is a fixed version of the gaussrand() function defined in a note above.

<?php
function gaussrand()
{
   static
$V2, $V1, $S;
   static
$phase = 0;
   if (
phase == 0)
   {
       while (
$S >= 1 || $S == 0)
       {
          
$V1 = 2 * (rand() / getrandmax()) - 1;
          
$V2 = 2 * (rand() / getrandmax()) - 1;
          
$S = $V1 * $V1 + $V2 * $V2;
       }
      
$X = $V1 * sqrt(-2 * log($S) / $S);
   }
   else
      
$X = $V2 * sqrt(-2 * log($S) / $S);
  
$phase = 1 - $phase;
   return
$X;
}
?>
joeldg at listbid.com
17-Jun-2003 04:14
/* This function return a gaussian distribution of floating-point
 * numbers.  This implementation is recommenden by D. Knuth, but due
 * originally to Marsaglia.
 *
 * Taken from the Comp.lang.c FAQ, maintained by Steve Summit.
 * ported to php from c by Joel De Gan
 * http://lucifer.intercosmos.net
 */

function gaussrand(){
   #static double V1, V2, S;
   $phase = 0;
   #double X;
   if (phase == 0) {
       while ($S >= 1 || $S == 0){
           $U1 = (double) rand() / 2147483647;
           $U2 = (double) rand() / 2147483647;
           $V1 = 2 * $U1 - 1;
           $V2 = 2 * $U2 - 1;
           $S = $V1 * $V1 + $V2 * $V2;
       };
       $X = $V1 * sqrt(-2 * log($S) / $S);
   }
   else {
       $X = $V2 * sqrt(-2 * log($S) / $S);
   }
   $phase = 1 - $phase;
   return $X;
}
jsheets at shadonet dot com
04-Jun-2003 10:49
The following function will create a random base64 encoded key, this is very useful for password reset schemes or anything where you want a random string.  To compare the string either compare the base64 encoded value or base64_decode it and compare that.

I do not use md5 because md5 results in only 1-9 and a-f in the string or 32^16 possibilities, by using the extended ASCII table and shuffling the array I am able to get a minimum of 32^127 possibilities with a 32 character string, using a longer string will make your value harder to guess still. A lot of machiens will have 32^255 possibilities in a decoded string.

function MakeResetKey($min_length = 32, $max_length = 64)
{
   $key = '';

   // build range and shuffle range using ASCII table
   for ($i=0; $i<=255; $i++) {
     $range[] = chr($i);
   }

   // shuffle our range 3 times
   for ($i=0; $i<=3; $i++) {
     shuffle($range);
   }

     // loop for random number generation
   for ($i = 0; $i < mt_rand($min_length, $max_length); $i++) {
     $key .= $range[mt_rand(0, count($range))];
   }

   $return = base64_encode($key);

   if (!empty($return)) {
     return $return;
   } else {
     return 0;
   }
}
donald at design dot net
07-Apr-2003 08:18
here's a REALLY simple random string generator, not as long and complicated as the others, but the same in theory:

function randstr($length = 16) {
   mt_srand((double)microtime()*10000);
   for($i=0;$i<$length;$i++) {
       $x = mt_rand(1,3);
       $str .= (($x == 1) ? chr(mt_rand(48,57)) : (($x == 2) ? chr(mt_rand(65,90)) : chr(mt_rand(97,122))));
   }
   return $str;
}
michael at something hotmail dot com
18-Nov-2002 12:49
An answer to demogracia:

Your first function "simpleRandString" is perfect, but the second function "randString" has a flaw: since you use the random generator to go into one of the three cases, every case will be used 1/3 of the time. Since case 1 has less possibilites than the others (10 vs. 26 and 26), the output can be more easily guessed: numbers will appear more often than average.

Here is the same function without this flaw:
function randString($length=16)
{
   $newstring="";
   if($length>0)
   {
       while(strlen($newstring)<$length)
       {
           $randnum = mt_rand(0,61);
           if ($randnum < 10)
               {$newstring.=chr($randnum+48);}
           elseif ($randnum < 36)
               {$newstring.=chr($randnum+55);}
           else
               {$newstring.=chr($randnum+61);}
       }
   }
   return $newstring;
}

You can make it a bit faster by not relying on "strlen" for every pass:
function randString($length=16)
{
   $newstring="";
   if($length>0)
   {
       while(strlen($newstring)<$length)
       {
           $randnum = mt_rand(0,61);
           if ($randnum < 10)
               {$newstring.=chr($randnum+48);}
           elseif ($randnum < 36)
               {$newstring.=chr($randnum+55);}
           else
               {$newstring.=chr($randnum+61);}
       }
   }
   return $newstring;
}
rugby at flipp dot net
10-Jul-2002 06:03
Just a small note for those zealots who want to avoid overseeding (which reduces randomness).

I have this small function to solve to get the best of both worlds:

(note the global variable)

----------------
$already_random = false;
function mt_seed(){
   global $already_random;
   if ($already_random) {
     list($usec, $sec) = explode(' ', microtime());
     mt_srand((float) $sec + ((float) $usec * 100000););
   }
$already_random=true;
}   
mt_seed();
$dice=mt_rand(1,6);
----------------

dead easy of course, but it might help some people.

If you are not sure what everybody is on about on this page, you can use this funtion (+global variable!) instead of make_seed(). Its a little better.
tom at globalmedia dot org
01-May-2002 09:24
To return a random decimal value between 0 and 1:
$randval=mt_rand()/mt_getrandmax();
guywhous at esphp dot com
11-Mar-2002 04:09
On an Apache 1.3.3 server, the seed mt_rand() uses resets to the same value every time the PHP file is uploaded.  This means that if mt_rand(1,500) returns 273 the first time it is used in your PHP file, it will return 273 again if you re-upload this file.  You have been warned.
demogracia at metropoliglobal dot com
02-Mar-2002 09:38
//
// Generates a random string with the specified length
// Chars are chosen from the provided [optional] list
//
function simpleRandString($length=16, $list="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"){
   mt_srand((double)microtime()*1000000);
   $newstring="";

   if($length>0){
       while(strlen($newstring)<$length){
           $newstring.=$list[mt_rand(0, strlen($list)-1)];
       }
   }
   return $newstring;
}

//
// Generates a random string with the specified length
// Includes: a-z, A-Z y 0-9
//
function randString($length=16){
   mt_srand((double)microtime()*1000000);
   $newstring="";

   if($length>0){
       while(strlen($newstring)<$length){
           switch(mt_rand(1,3)){
               case 1: $newstring.=chr(mt_rand(48,57)); break;  // 0-9
               case 2: $newstring.=chr(mt_rand(65,90)); break;  // A-Z
               case 3: $newstring.=chr(mt_rand(97,122)); break; // a-z
           }
       }
   }
   return $newstring;
}
psychoborg at yahoo dot com
31-Jan-2002 09:34
ok, an update to my last comment

well, the rand function works, but looks like it has a limitation to it.

look at this :
function calcres($number)
{
   global $Supplies;
   srand ((double) microtime() * 1000000);
       $retval = 0;
   $a = 0;
   if ($a!=$number)
   {
       do
       {
           $a++;
         #  $tmp = rand(0,3+
         # the rand is limited in the function,  Especcially with the current formula that im using here. but the fix is quite simple. just change the rand to mt_rand this will increase your random findings and stablize your php program,
($supplies+$retval));
           if ($tmp<20) $retval++;
       }while($a<$number);
   }
   return $retval;
}

This function will work best with the mt_rand runction and not only that, it is most defanitly more stable. meaning you will not hit the limitation that will cause the SQL event out of range error.
12-Jan-2002 07:33
There is a intresting article on Developers resources about
Pseudo-random PHP functions and truly random number generators.
http://www.developers-resources.com/stories.php?story=01/12/03/3988084

They have wrote a function that randomly retrieves a random number. Either generated by the computer pseudo-randomly or from one of two truly random number sites.
amcclung at stetson dot edu
18-Apr-2001 10:27
Here's an elegant way of generating a random float value within a certain range:

$range = $upperBound-$lowerBound;
$num = $lowerBound + $range * mt_rand(0, 32767)/32767;

You should now have a floating point number between your $lowerBound (i.e. 0.5) and $upperBound (0.75) values.
gerwout at minso dot nl
27-Mar-2001 05:29
Don't forget to do mt_srand() before the mtrand() or you wil get the same values every time you'll go back to the same page.<br>Not when you refresh the page, only when you open the page in a new browserwindow and the history is empty.
mrdlinux at yahoo dot com
21-Jul-2000 07:02
And for those who prefer scaling:

mt_rand() / RAND_MAX * (Max - Min) + Min;

<mt_getrandmaxmt_srand>
 Last updated: Sun, 12 Sep 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Tue Sep 14 05:16:21 2004 CEST