Biased Random Value From Array With PHP

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.

function biasedRandom($numbers){
 $total = 0;
 foreach($numbers as $number=>$weight){
  $total += $weight;
  $distribution[$number] = $total;
 };
 $rand = mt_rand(0,$total-1);
 foreach($distribution as $number=>$weights){
  if($rand<$weights){
   return $number;
  };
 };
}

This function is used in the following way.

//set up array
$array = array('one'=>100,
 'two'=>100,
 'three'=>100,
 'four'=>500);
 
// get biased random number
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.
CAPTCHA
2 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.