Forum Moderators: coopster

Message Too Old, No Replies

how to use php random function

         

abiao

4:04 am on Feb 2, 2008 (gmt 0)

10+ Year Member



how to use php random function to generate 5 numbers one time, and each number is from 1 to 60?

tks

wheelie34

9:54 am on Feb 2, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I use this

srand(time());
$random = (rand()%15);
$random2 = (rand()%15);

To generate numbers between 0 + 15 for a captcha field on a form, it does what I want.

jatar_k

2:09 pm on Feb 2, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



[php.net...]
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

you just call rand 5 times

rand(1,60) // for your range

then depending on how you wanted to display them, you could echo them right away, put them in an array or seperate vars.

abiao

8:22 am on Feb 3, 2008 (gmt 0)

10+ Year Member



i have tested the function, but sometimes it generated the same result, i need 5 different results.

jatar_k

2:05 pm on Feb 3, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



then put them in an array and check the array on the next iteration to see if the value already exists

$myrandnum = array(); 
for ($i=0;$i<5;$i++) {
$mynum = rand(1,60);
if (!in_array($mynum,$myrandnum)) $myrandnum[] = $mynum;
else $i--;
}