New way to learn PHP Example

PHP Random Number

How to generate random number or id

Rand () function is used to generate a random number it takes two integer optional parameters. You can use mt_rand () function that generates a random number faster than and rand function function.

Simple method to generate unique number within specific range



printf("Unique number =%d
",$r); ?>


rand() function is a PHP built-in function that generates a unique number. If you want to generate a unique number within a range, then define the start and end point of random number. If you define the start and end point, then the unique number will be in between.
Start point = 10
End point = 100
Number can =11
Number can =99
Number cannot =101
Number cannot =09

If you have not decide the start and end point, then rand function automatically create a unique number without any range, it’s totally depend on function.

Generate random number without specific range



printf(" Number =%d",$r);



In this example, a random number is created without any range. It can be any number like 20, 5289, 120 etc.

Generate random numbers using loop




echo "Number between 10 to 100
"; for($i=0;$i<=10;$i++) { $r=rand($min,$max); printf("Nnumber =%d
",$r); } ?>


In this example, the start point is 10 and the end point is 100 and in seventh the line there is a simple echo statement that display the statement. According to the line number 11 to 14 is a for loop that’s run 10 times, a variable $r store the random number and printf function print 10 number.

Generate random number using date




$number=rand($date_range  , $currentdate);

echo $number;



In the above example, start point is the current date and the end point is specified in this program, so the number could be 20120312 etc.

Complex random number


$random= rand(0,999999999);
$a= $t+$random;
printf(" Random number =%d",$a);
echo "
"; $un= uniqid(); $conct = $a.$un; //its also refer a unique id printf("Random number =%d
",$conct); $ud = md5($conct.$un); echo "But its more accurate="; echo $ud; ?>


In this example first store the current date in $time1 variable, then create a unique number from zero to 99999999 and then add unique number and time, it’s also a good random number. After that call uniqid (its create a unique id) function to a variable $un and concatenate $un and $a, call md5 (calculates the MD5 hash of a string). it’s very secure.


Random id refer as product id in many websites.


Each day provides its own gifts.