Pseudo random numbers in php

Posted by pg on Stack Overflow See other posts from Stack Overflow or by pg
Published on 2010-04-15T00:58:35Z Indexed on 2010/04/15 1:03 UTC
Read the original article Hit count: 462

Filed under:
|
|

I have a function that outputs items in a different order depending on a random number. for example 1/2 of the time Popeye's and its will be #1 on the list and Taco Bell and its logo will be #2 and half the time the it will be the other way around. The problem is that when a user reloads or comes back to the page, the order is re-randomized. $Range here is the number of items in the db, so it's using a random number between 1 and the $range.

  $random = mt_rand(1,$range);
  for ($i = 0 ; $i < count($variants); $i++) {
    $random -= $variants[$i]['weight'];
    if ($random <= 0) {
      $chosenoffers[$tag] = $variants[$i];
      break;
    }
  }

I went to the beginning of the session and set this:

if (!isset($_SESSION['rannum'])){
    $_SESSION['rannum']=rand(1,100);
    }

With the idea that I could replace the mt_rand in the function with some sort of pseudo random generator that used the same 1-100 random number as a seed throughout the session. That way i won't have to rewrite all the code that was already written. Am I barking up the wrong tree or is this a good idea?

© Stack Overflow or respective owner

Related posts about php

Related posts about pseudo-random-numbers