mt_rand(): generates a random integer using the Mersenne Twister algorithm

echo mt_rand(10,100); // Output is 32 
Syntax
int mt_rand ( int $min, int $max)
ParameterDESCRIPTION
$minOptional : Minimum range of random number to be generated.
$maxOptional : Maximum range of random number to be generated.

Output is a random value.

This function uses Mersenne Twister Random Number Generator.

Example

echo mt_rand();
Out put is ( will chage )
2147483647

Example: Using mt_srand() for Reproducible Results

mt_srand(100); 
echo mt_rand(1, 100);  // Output: 52
echo mt_rand(1, 100);  // Output: 5

Example: Generating Random Float Numbers

$min = 0;
$max = 1;
echo $min + (mt_rand() / mt_getrandmax()) * ($max - $min);  // Output: Random float between 0 and 1

Example: Generating Random Passwords

$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = '';
for ($i = 0; $i < 8; $i++) {
    $password .= $characters[mt_rand(0, strlen($characters) - 1)];
}
echo $password;  // Output: Random 8-character password

Example: Generating Random Colors

$red = mt_rand(0, 255);
$green = mt_rand(0, 255);
$blue = mt_rand(0, 255);
echo sprintf("#%02x%02x%02x", $red, $green, $blue);  // Output: Random hex color

Example: Random Shuffle of an Array

$arr = [1, 2, 3, 4, 5];
shuffle($arr);
print_r($arr);  // Output: Array elements in random order

Math Functions getrandmax(): Getting highest random number max() function
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer