random

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!

/* this function expects either an array
 * ordered by weight, or with exact weights
 * as it's array indices.
 * it will return a randomly selected value.
 */
function wrand($data) {
	$totalw = $curw = 0;
	
	foreach ($data as $i => $val) {
		$totalw += $i;
	}
	
	$rand = rand(0,$totalw);
	
	foreach ($data as $i => $val) {
		if ($curw >= $rand) return $val;
		$curw += $i;
	}
	
	return array_pop($data);
}