[PHP 4, PHP 5, PHP 7, PHP 8]
mt_rand — Generate a random value via the Mersenne Twister Random Number Generator
Description
mt_rand[]: int
mt_rand[int $min
, int $max
]: int
Many random number generators of older libcs have dubious or unknown characteristics and are slow. The mt_rand[] function is a drop-in replacement for the older rand[]. 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 mt_getrandmax[]. If you want a random number between 5 and 15 [inclusive], for example, use mt_rand[5,
15]
.
Parameters
min
Optional lowest value to be returned [default: 0]
max
Optional highest value to be returned [default: mt_getrandmax[]]
Return Values
A random integer value between min
[or 0] and max
[or
mt_getrandmax[], inclusive], or false
if max
is less than min
.
Changelog
7.2.0 | mt_rand[] has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines. |
7.1.0 | rand[] has been made an alias of mt_rand[]. |
7.1.0 | mt_rand[] has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand[] with MT_RAND_PHP as the second parameter.
|
Examples
Example #1 mt_rand[] example
The above example will output something similar to:
Notes
Warning
min
max
range must be within the range
mt_getrandmax[]. i.e. [max
- min
]
the differences reduce when reducing the pixels of the image.. infact for a 100x100 pixel image the noise produced from the rand function is much more realistic than how it is for a 400x400 image: //oi39.tinypic.com/5k0row.jpg
[rand is on the left, mt_rand on the right]
chagenbu at php dot net ¶
15 years ago
The algorithm used by mt_rand[] changed in PHP 5.2.1. If you are relying on getting the same sequence from mt_rand[] after calling mt_srand[] with a known seed, upgrading to PHP 5.2.1 will break your code. See //bugs.php.net/bug.php?id=40724 for something of an explanation; there is no workaround.
Hayley Watson ¶
9 years ago
Another graphical comparison of rand[] and mt_rand[]. It effectively draws a graph showing how the last generated number affects the next by plotting the numbers in consecutive pairs against each other.
falkartis at gmail dot com ¶
8 years ago
I wrote another function to get a random float, if its not precise enougth jut add some '0' to the $mul parameter.
I made following tests:
contact at sheyd dot fr ¶
10 years ago
To quickly build a human-readable random string for a captcha per example :
Note that I have removed q and y from $chars to avoid readability problems.
Miller ¶
9 years ago
Another generic random string function, but very small and fast.
j dot s dot shiuan at gmail dot com ¶
11 years ago
Another good way to get a random float is to divide the result of mt_rand.
Let's say we want a float between 0.75 and 1.25.
zolaar at nothanks dot com ¶
15 years ago
a better [and likely faster] way to generate a random 6-digit hex string:
The mt_rand function won't give you a number outside the bounds you asked for -- no need to and-off the top bits -- and the sprintf function has params for length-padding & hexidecimal output. It's likely faster because most of the work is being done by the wicked fast C functions that PHP sits on top of, though YMMV in that dept.
geompse at yopmail dot com ¶
14 years ago
mt_rand[] is not faster than rand[] !
Tested over 100'000 iterations, with none/various/random arguments, mt_rand is always 3% slower than rand[].
rok dot kralj at gmail dot com ¶
15 years ago
mt_rand function returns just a whole numbers. If you want a random float, then here's an elegant way:
Nikhil S. ¶
2 years ago
A nifty function to generate pretty coupon codes. This will generate unique coupon codes and you don't have to do a database check whether the code already exists.
fabiovh on gmail ¶
14 years ago
performance: for a repetitive task, it's much faster not to use the limit parameters, as shown below. just use the % operator.
$t=microtime[true];
for[$i=0;$i
mark omohundro, ajamyajax dot com ¶
13 years ago
just another example: both of these routines return a random decimal number between -1 and 1... since rand[] only returns a max 'integer' value while mt_rand[] return a max 'long' value -- at least on some platforms -- mt_rand[] could be the better precision choice for some on any variation to this routine [but i don't think it matters here]:
nowhere at where dot net ¶
17 years ago
Allows characters 0-9, a-z
Weighted [and tested] ok.
nospamremove dot francois dot gannaz at silecs dot info ¶
6 years ago
rand[] comes from the libc, and mt_rand[] is internal to PHP. So the differences vary with their respective versions.
On a 64b Debian Stretch with PHP 5.6.21, there is no visible difference: //oi64.tinypic.com/2nkqas6.jpg
This image compares the two functions. In the top half with random points, in the lower half with random intensity on each point. This is totally different from what was obtained 4 years ago in another note, with an unknown environment.
Here is the code for this visual comparison.
Jeff Cours ¶
7 years ago
With PHP 5.3.3, we're seeing odd behavior on 32 bit Linux.
This works fine on 64 bit Linux:
but on our 32 bit Linux development server, it's always yielding "00000000".
On that same machine, this:
seems to always yield either 00000000 or a number in the range fffffff2 to ffffffff. This:
gives numbers where the last two digits vary, and so on through at least 0xF0000000.
However, this:
seems to be well-behaved.
The moral? On 32 bit systems, be careful about crossing the signed number boundary, 0x7FFFFFFF.
nilesh at itech7 dot com ¶
12 years ago
A class to generate 99.5% unqiue strings. I found that there is only one or two characters common between two subsequent strings.
Mark Seecof ¶
14 years ago
If you need some pseudorandom bits for security or cryptographic purposes [e.g.g., random IV for block cipher, random salt for password hash] mt_rand[] is a poor source. On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this:
NB: it is generally safe to leave both the attempt to read /dev/urandom and the attempt to access CAPICOM in your code, though each will fail silently on the other's platform. Leave them both there so your code will be more portable.
Anonymous ¶
18 years ago
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.
Armond Carroll
Robin Leffmann ¶
11 years ago
Fast, pseudo-random binary data generation using mt_rand[]: