<?php
$gender = array(
'Male'=>30,
'Female'=>50,
'U' =>20);
$total = array_sum(array_values($gender));
$current = 0;
$rand = rand(1,$total);
foreach ($gender as $key=>$value)
{
$current += $value;
if ($current > $rand)
{
echo $key;
break;
}
}
?>
At the moment I am trying to generate a random value based on a weighted percentage. In this example, Male has a 30% chance, female 50 and U 20% chance. I had a feeling that the logic in the code was wrong, so I ran script a 100 times, and normally you would get 30 Males, however that wasn't the case. Is there a smarter way to do this?