<?php
function numberOfDecimals($value)
{
if ((int)$value == $value)
{
return 0;
}
else if (! is_numeric($value))
{
// throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
return false;
}
return strlen($value) - strrpos($value, '.') - 1;
}
function roulette($items)
{
$sumOfPercents = 0;
foreach($items as $itemsPercent)
{
$sumOfPercents += $itemsPercent;
}
$decimals = numberOfDecimals($sumOfPercents);
$multiplier = 1;
for ($i=0; $i < $decimals; $i++)
{
$multiplier *= 10;
}
$sumOfPercents *= $multiplier;
$rand = rand(1, $sumOfPercents);
//echo "max percent = {$sumOfPercents}\n";
//echo "rand = $rand\n";
$rangeStart = 1;
foreach($items as $itemKey => $itemsPercent)
{
$rangeFinish = $rangeStart + ($itemsPercent * $multiplier);
//echo "$itemKey in [$rangeStart, $rangeFinish]\n";
if($rand >= $rangeStart && $rand <= $rangeFinish)
{
return $itemKey;
}
$rangeStart = $rangeFinish + 1;
}
}
$items = array('item-1' => 0.25, 'item-2' => 0.5, 'item-3' => 5, 'item-4' => 4.25333);
echo roulette($items);