Random numbers ... it works, but why like this?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Random numbers ... it works, but why like this?

Post by Stryks »

Hi all,

Just a simple question really. I got some help with a random number generation function, and the function works well enough, but I would really like to know why it has been made the way it is.

Code: Select all

function _rand_num($min = null, $max = null)
{
   static $seeded;

   if (!$seeded) {
      mt_srand((double)microtime()*1000000);
      $seeded = true;
   }

   if (isset($min) && isset($max)) {
      if ($min >= $max) {
         return $min;
      } else {
         return mt_rand($min, $max);
      }
   } else {
      return mt_rand();
   }
}
In particular, what I dont understand is the whole ...

Code: Select all

static $seeded;

   if (!$seeded) {
... bit.

Isnt it just redundant. Wont $seeded, although static, always be valueless and thus always make seeding necessary.

If not, why. And what is the purpose if it has one.

Thanks. :?
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Oh, OK ... I get it.

If it is called more than once in a page load, it only stops to seed the number generator the first time around.

Cool 8)
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Actually, while I'm here.

The manual says that you dont need to call mt_srand anymore as it is automatic. However, if I dont call it beforehand, the number it returns is always the same.

Any reason? Or is it just a new development.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Whether you need to seed should depend on your PHP version - are you using 4.2 or above? - but I've had iffy results and just leave the seeding in to be sure.

Mac
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Thanks :D
Post Reply