PHP: Generating a random number between Min and Max

Last updated on October 21, 2022 A Goodman Loading... Post a comment
Image source: Pixabay

In order to generate a random number within a given range, you can use the rand() or the mt_rand() functions.


$x = rand(10, 20);
$b = mt_rand(20, 30);

// Printing the output
echo $x;
echo '<br/>';
echo $b; 

Output (the output is not consistent will change each time you execute your code):


Note: mt_rand() is 4 times faster than rand(). You can find more information about this in the official docs.

Further reading:

I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.

Notify of
Inline Feedbacks
View all comments

Related Articles