I was wondering if there is a function, or how to write a clever one that can make the task. Let's imagine array like this:
$arr = array(25, 35, 40);
I'd like to get key of random value from this table, but I'd like to have 25% for $arr[0], 35% for $arr[1], and 40% for arr[2] - depending on the values. There might be any number of values in array, and the sum is not always 100(%) - this is just example.
I figured out such solution:
$arr = array(123, 1856, 84, 84, 2, 654, 321);//just an example
$temp = 0;
$rand = mt_rand(1, array_sum($arr));
foreach ($arr as $key => $value)
{
$temp += $value;
if ($temp >= $rand)
{
$random_key = $key;
break;
}
}
echo 'key of "random" element is '.$random_key;
Can it be done better?
Aucun commentaire:
Enregistrer un commentaire