Thursday, 12 September 2013

Generating random variable from array based on weight percentage

Generating random variable from array based on weight percentage

I have the following code:
<?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;
}
}
?>
However, when I run it, I sometimes get:
MaleFemaleU
Or:
FemaleU
I set the values for the $gender arrays, and would like to generate the
gender based on the percentage given, i.e. in this case: male 30, female
50, and unknown 20.

No comments:

Post a Comment