rand() can generate a pseudo-random integer in an inclusive range. It is suitable for ordinary non-security uses; use random_int() when the value must be unpredictable.
$number = rand(1, 10);
echo $number;
echo rand(); // Output varies
echo rand(8,10); // Random Output starting from 8 to 10
Syntax
int rand(int $min, int $max)
$min and $max are optional together and define the inclusive range. Since PHP 7.1, rand() uses the same generator as mt_rand(). For newly written code, prefer Random\Randomizer; use random_int() when unpredictability is required.
This example creates five digits. It is a display string, so a leading zero is preserved.
<?Php
$no_of_digits=5;
$var='';
for($i=1; $i<=$no_of_digits; $i++){
$var .=rand(0,9);
}
echo "<br>Random Value = $var";
?>
Example output:
Random Value = 33369
$random_float = mt_rand() / mt_getrandmax();
echo $random_float;
Manual seeding changes the global Mersenne Twister state. Use it only when you deliberately need repeatable demonstration or test data. See mt_srand().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| princy | 02-02-2012 |
| how to generate the random number in php | |