Do you need to make a random decision, but you want some options to have a higher likely-hood of getting picked? The weighted_random function below accomplishes this and its one I've been using for a while.
The example below will choose 'rain' 80% of the time and 'sun' 20% of the time. The sum of the weights(keys) is arbitrary, so I chose 100 because it's easier to think of percentages that way. However you could use any integer value for the weighting.
$options = array(80=>'rain',20=>'sun');
echo weighted_random(array_keys($options), array_values($options));
function weighted_random($weights, $values){
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(0, array_sum($weights));
while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $values[$i];
}
Now supposed you just want to toss a coin, but you want to determine the likely-hood of it returning True of False. Here's a simpler wrapper function that makes this easy. You simply pass in a value between 0 and 100 and it will return True that percentage of the time. So, if you pass in 50, it will return True 50% of the time, 80=80%, 35=35%, and so on.
echo percentage_decision(50);
function percentage_decision($percentage){
$percentage = ($percentage>100)?100:$percentage;
$percentage = ($percentage<0)?0:$percentage;
$margin = 100-$percentage;
$weights = array(1=>$percentage,0=>$margin);
return (weighted_random(array_keys($weights), array_values($weights)) == 1);
}
I hope someone finds this helpful. If you you know of a drastically more efficient way of accomplishing this, please post your suggestions :)