Jump to content

PHP - Random Number Probelms


Fruitpastles

Recommended Posts

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

Link to comment
Share on other sites

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.
Link to comment
Share on other sites

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

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...