PHP Numbers
Generating Predictable Random Numbers
Problem
You want to make the random number generate predictable numbers so you can guar‐antee repeatable behavior.
Solution
Seed the random number generator with a known value using mt_srand() (or srand()):<?php
function pick_color() {
$colors = array('red','orange','yellow','blue','green','indigo','violet');
$i = mt_rand(0, count($colors) - 1);
return $colors[$i];
}
mt_srand(34534);
$first = pick_color();
$second = pick_color();
// Because a specific value was passed to mt_srand(), we can be
// sure the same colors will get picked each time: red and yellow
print "$first is red and $second is yellow.";
Discussion
For unpredictable random numbers, letting PHP generate the seed is perfect. But seeding your random number generator with a known value is useful when you want the random number generator to generate a predictable series of values.
This is handy when writing tests for your code. If you are writing a unit test to verify the behavior of function that retrieves a random element from an array, the condition you’re testing for will change each time the test runs if your numbers are really random.
But by calling mt_srand() (or srand()) with a specific value at the beginning of your test, you can ensure that the sequence of random numbers that is generated is the same each time the test is run.
No comments:
Post a Comment