In this tutorial, we would love to share with you how to generate 2,4,6,10,12 digit unique random number in PHP? Let’s see how to generate random number in php
PHP rand() function
The PHP rand() is inbuilt PHP function. Which is used to generate a random integer number.
Syntax
The basic syntax of rand() function is following:
rand(); or rand(min,max);
Parameters of rand() function
- min:- This a first parameter of this function and it is optional. Specifies the minimum/smallest/lowest number to be returned. Default is 0
- max:- This a second parameter of this function and it is also optional. Specifies the maximum/largest/highest number to be returned.
Example of rand() function
<?php
echo(rand() . "<br>");
echo(rand(10,99) . "<br>"); // generate 2 digit unique random number in php
echo(rand(1000,9999) . "<br>"); // generate 4 digit unique random number in php
echo(rand(100000,999999) . "<br>"); // generate 4 digit unique random number in php
echo(rand(10000000,99999999) . "<br>"); // generate 8 digit unique random number in php
PHP mt_rand() function
The PHP mt_rand () is the inbuilt PHP function. Which is used to generate random integer numbers. This function uses the Mersenne Twister algorithm.
Syntax
The basic syntax of mt_rand() function is the following:
mt_rand(); or mt_rand(min,max);
Parameters of mt_rand() function
- min:- This a first parameter of this function and it is optional. Specifies the minimum/smallest/lowest number to be returned. Default is 0
- max:- This a second parameter of this function and it is also optional. Specifies the maximum/largest/highest number to be returned.
Example of mt_rand() function
<?php
echo(mt_rand() . "<br>"); //
echo(mt_rand(10,99) . "<br>"); // generate 2 digit random number in php
echo(mt_rand(1000,9999) . "<br>"); // generate 4 digit random number in php
echo(mt_rand(100000,999999) . "<br>"); // generate 4 digit random number in php
echo(mt_rand(10000000,99999999) . "<br>"); // generate 8 digit random number in php
Note:
The PHP mt_rand() function generate a better random value. And also this function is 4 times faster than rand() function.
Comments are closed.