Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP mt_rand() Function
The 'mt' prefix in function's name stands for Mersenne Twister. The mt_rand() function returns a random integer using the Mersenne Twister Random Number Generator algorithm. This function is a drop−in replacement for PHP's rand() function and is four times faster. The default range is between 0 and the platform−specific mt_getrandmax() value (2147483647 on 64−bit systems).
Syntax
mt_rand() : int mt_rand(int $min, int $max) : int
Parameters
| Parameter | Description |
|---|---|
| min | Lower limit of the range. Default is 0 |
| max | Upper limit of the range. Default is mt_getrandmax()
|
Return Value
Returns a random integer between min and max (inclusive) using the Mersenne Twister algorithm. This function is not suitable for cryptographic purposes.
Example 1: Basic Usage
Generate random numbers with and without specified range ?
<?php
echo "mt_rand() = " . mt_rand() . "<br>";
echo "mt_rand(1, 10) = " . mt_rand(1, 10) . "<br>";
echo "mt_rand(100, 999) = " . mt_rand(100, 999) . "<br>";
?>
mt_rand() = 1804289383 mt_rand(1, 10) = 7 mt_rand(100, 999) = 542
Example 2: Float Parameters
When float values are passed, they are automatically converted to integers ?
<?php
echo "mt_rand(10.5, 50.95) = " . mt_rand(10.5, 50.95) . "<br>";
echo "mt_rand(2.8, 8.9) = " . mt_rand(2.8, 8.9) . "<br>";
?>
mt_rand(10.5, 50.95) = 31 mt_rand(2.8, 8.9) = 5
Example 3: Getting Maximum Value
Check the maximum possible random value on your system ?
<?php
echo "Maximum mt_rand value: " . mt_getrandmax() . "<br>";
echo "Random between 0 and max: " . mt_rand(0, mt_getrandmax()) . "<br>";
?>
Maximum mt_rand value: 2147483647 Random between 0 and max: 1598374920
Conclusion
The mt_rand() function provides fast, high−quality random number generation using the Mersenne Twister algorithm. Use it for general purposes but avoid it for cryptographic applications where random_int() is preferred.
