Fruitpastles Posted July 4, 2007 Posted July 4, 2007 Hi, I'm trying to get this script to work. It is supposed to fill an array with 6 different random numbers, but for some reason it fills it with the same number, despite me recalling the function to generate the numbers. <?php function random(){ //function to generate random number srand(time()); $random = (rand()%6)+1; return $random; } for($i=1;$i<7;$i++){ //fill '$code' array, with '$random' $code[$i] = random(); } for($i=1;$i<7;$i++){ //output array - debug echo($code[$i]); echo("<br>"); } ?> Any help is greatly appreciated :D Quote
SomeoneE1se Posted July 4, 2007 Posted July 4, 2007 <?php function random(){ srand(time()); $code = array(rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6)); return $code; } var_dump(random()); ?> Quote
cooper Posted July 4, 2007 Posted July 4, 2007 The rand function works with a pseudo random number generator. I.e. it's deterministic (as opposed to random) from a given seed. You can get away with that for most applications if your seed is sufficiently unique and hard to guess. The problem with your program is that when you seed your PRNG you're effectively resetting it. And since you're seeding your PNG with a rather constant value (the amount of seconds since 1-1-1970) you end up with the same number for all 6 positions in your array in almost all cases. Also, both of you, please consider the PHP.net documentation of the rand() method, which clearly states: 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. Quote
SomeoneE1se Posted July 4, 2007 Posted July 4, 2007 The rand function works with a pseudo random number generator. I.e. it's deterministic (as opposed to random) from a given seed. You can get away with that for most applications if your seed is sufficiently unique and hard to guess. The problem with your program is that when you seed your PRNG you're effectively resetting it. And since you're seeding your PNG with a rather constant value (the amount of seconds since 1-1-1970) you end up with the same number for all 6 positions in your array in almost all cases. Also, both of you, please consider the PHP.net documentation of the rand() method, which clearly states: 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. I knew that too, I don't know why I left that in there. Thanks cooper Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.