Let's have an array

Need a function of randomness with regulation chances fall test with 50% chance, tost - 10%, tost1 - 40%

`$arr = ['test' => 50, 'tost' => 10, 'tost1' => 40];`

Need a function of randomness with regulation chances fall test with 50% chance, tost - 10%, tost1 - 40%

asked June 14th 19 at 19:08

2 answers

answered on

Solution

```
function chance($arr) {
$total = array_sum($arr);
$rand = rand(1, $total);
foreach($arr as $key => $prob) {
$rand -= $prob;
if ($rand <= 0) {
return $key;
}
}
}
print chance(array('test' => 50, 'tost' => 10, 'tost1' => 40));
```

answered on June 14th 19 at 19:12

```
$arr = ['test' => 50, 'tost' => 10, 'tost1' => 40]; // sum should be 100
sort($arr);
$n = rand(0, 100); // well, or then to use array_sum($arr)
$sum = 0;
foreach ($arr as $i => $r) {
$sum += $r;
if ($sum >= $n) {
echo $i;
break;
}
}
```

Find more questions by tags PHP