Biased Random Value From Array With PHP

10th March 2008 - 1 minute read time

Sometimes you will want to get a random value form an array in a biased random way, that is, you will want certain values to be returned more than others. Here is a function that will generate a single key from an array, with a greater change of a higher value being retrieved.

  1. function biasedRandom($numbers){
  2. $total = 0;
  3. foreach($numbers as $number=>$weight){
  4. $total += $weight;
  5. $distribution[$number] = $total;
  6. };
  7. $rand = mt_rand(0,$total-1);
  8. foreach($distribution as $number=>$weights){
  9. if($rand<$weights){
  10. return $number;
  11. };
  12. };
  13. }

This function is used in the following way.

  1. //set up array
  2. $array = array('one'=>100,
  3. 'two'=>100,
  4. 'three'=>100,
  5. 'four'=>500);
  6.  
  7. // get biased random number
  8. echo biasedRandom($array);

The key that is generated the most by the function is four because it has a higher value than the rest and will therefore 'weigh' a lot more.

Add new comment

The content of this field is kept private and will not be shown publicly.