wrand(); // A PHP weighted randomization function
Dan from todaywasawesome just asked me to help him with a weighted randomization function in PHP. I thought my solution was cool, if a bit simplistic. Like everything else I want to keep around, I’m posting it in my blag. Enjoy!
<?php
/**
* This function expects an array with weights
* as its array indices. You should not use a
* simple array — e.g. array('a', 'b', 'c'). Since
* the first item in an array like this has index 0,
* it will never be selected.
*
* It will return a randomly selected value.
*/
function wrand($data) {
$totalw = array_sum(array_keys($data));
$rand = rand(1, $totalw);
$curw = 0;
foreach ($data as $i => $val) {
$curw += $i;
if ($curw >= $rand) return $val;
}
return end($data);
}