Blog by Debabratta Jena
How to generate random number in php

How to generate random number in php

Published on Oct 13, 2020
Two ways we can generate random numbers in php using rand() or mt_rand() functions. But output of these functions can generate repeated numbers for smaller range or over longer period of time. So we should use these numbers only for testing purposes or smaller websites where security is not a issue.

So, lets talk about these functions.

Note : If you want to generate cyptographically secured numbers then you shoud see this article. How to generate cryptographicaly secured numbers.

Syntax :
rand(number1,number2)
where number1 and number2 is the lower and upper range you provide. Number generated will be in between these two values.

Another function mt_rand() also performs the similar functions but with more uniquness in output and greater speed. mt_rand() functon uses the Mersenne Twister algorithm.

Syntax :
mt_rand(number1,number2)
Howevere parameters passsed to both the functions are optional. We can simply call the function without passing any arguments, in that case value generated will be of random length.

mt_rand() function produces a better random value and is 4 times faster than rand().

If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).

If repetition of number is not allowed in your project, use mt_rand() instead.
If you like this article, share the knowledge with your friends. It will inspire me to write more.