rand(): Random integer generator

echo rand(); // Random Output 16513
echo rand(8,10); // Random Output starting from 8 to 10 
Syntax
rand ( min,max);
min ,max : (Optional) Minimum and maximu value ( both inclusive ) of random integer to be generated ( both to be given )

We can generate random value by using rand() PHP. We can specify a range and the random value between those two ranges (inclusive) will be generated.
This output is not cryptographically secure values , so for cryptographically secure value, consider using random_int(), random_bytes
Note that here we are generating a random number only. To get any random characters we can use arrays. The details on how to generate random characters is available here.

Random number of different length

We can create a script to generate random number of different length. Let us try to develop a script to print random number of 5 character length.

Here it is
<?Php
$no_of_digits=5;
$var='';
for($i=1; $i<=$no_of_digits; $i++){
$var .=rand(0,9);
}
echo "<br>Random Value = $var"; 
?>
Output is here
Random Value = 33369

Example: Generating Random Floats

$random_float = mt_rand() / mt_getrandmax();
echo $random_float;

Example: Seeding Random Number Generator

mt_srand(123); // Seed the generator
echo mt_rand()."<br>";  // Output: Same number every time the script is run
echo mt_rand();  // Output: Same number every time the script is run

Example: Resetting the Seed

mt_srand(987);
echo mt_rand();  // Output will change with a different seed value

How to generate random string having alphabets and digits

Math Functions random_int(): cryptographically secure pseudo-random integers Rounding off value
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







princy

02-02-2012

how to generate the random number in php




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