- var_dump: documentation ( source)
- array_sum: documentation ( source)
- mt_rand: documentation ( source)
- array_fill: documentation ( source)
<?php
function weight($array)
{
$rnd = mt_rand(0, array_sum($array));
foreach ($array as $k=>$v)
{
if ($rnd <= $v)
{
return $k;
}
$rnd -= $v;
}
}
$weights = [100, 200, 1000];
$values = array_fill(0, count($weights), 0);
for ($x = 0; $x < 1000; $x++)
{
// at the position returned by the weight function, +1
$values[weight($weights)]++;
}
var_dump($values);