简体   繁体   中英

Pseudo random numbers in php

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 \\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?

What should to the job is:

<?php
srand(1);
echo rand();
// 1804289383
srand(1);
echo rand();
// 1804289383
?>

or respective

<?php
mt_srand(1);
echo mt_rand(1, 100);
//58
mt_srand(1);
echo mt_rand(1, 100);
//58
?>

and saveing the seed in the session like you said

Answering the question: It depends. It is one approach*.

But check out: http://www.php.net/manual/en/function.mt-srand.php . The PHP mt_rand is a Mersenne Twister, which is a PRNG (already) and has a seed function.

*However, if the backing source changes, you've still got it wrong. Oops :-/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM