$num = mt_rand(0, array_sum($weights));

you should use

$num = mt_rand(1, array_sum($weights));

because mt_rand includes both min and max values in its outputs.

With the current version, if you have

$weights = [0, 1];

you will still get a fifty-fifty distribution among the two values (which is obviously not desired).

Array (

‘id’ => ‘weight’

}

$cweights = count($weights);

for ($i=0; $i<$cweights; $i++) {

Thanks for the code I think I’ll use it.

]]>function weighted_random_simple($values, $weights){

$total = array_sum($weights);

$n = 0;

$num = mt_rand(1, $total);

foreach ($values as $i => $value) {

$n += $weights[$i];

if ($n >= $num){

return $values[$i];

}

}

}

in mt_rand() the $min value must be 1, not zero, since $min and $max are both included. Begining with zero you give the first element the probability of zero plus the probability of the weight.

]]>