rand(): Random integer generator

Generate an ordinary pseudo-random integer

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 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.

Generate a fixed-length digit string

This example creates five digits. It is a display string, so a leading zero is preserved.



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"; 
?>

Example output:

Random Value = 33369

Example: Generating Random Floats

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

Repeatable sequences belong in the mt_srand() lesson

Manual seeding changes the global Mersenne Twister state. Use it only when you deliberately need repeatable demonstration or test data. See mt_srand().


How to generate random string having alphabets and digits

Math Functions random_int(): cryptographically secure pseudo-random integers Rounding off value


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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer