pTutorial

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

<?php

$r=rand(200,500);

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

Explanation

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

<?php

$r=rand();

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

?>

Explanation

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

<?php

$min=10;

$max="100";

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

Explanation

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

<?php

$currentdate=date('Ymd'); 

$date_range=20120314;

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

echo $number;

?>

Explanation

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

<?php

$time1=time();
$t=$time1; 
$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; ?>

Explanation

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.


QUOTES OF THE DAY

Knowledge without integrity is dangerous and dreadful.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER