3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $input = [.1, .2, .7]; function weightedSelector($input, $value){ foreach ($input as $key => $value){ $total = array_sum($input); $previous = array_sum(array_slice($input, 0, $key)); $percentage = $total - $previous; print_r($total." ".$previous." ".$percentage); if ($value <= $percentage){ return $key; } } } foreach ([.1, .15, .2, .29, .3, .4, .5, .8, .99, .66] as $value){ print_r(weightedSelector($input, $value)." : ".$value); // print_r("\n"); }
based on fOLe1
Output for 5.6.0 - 5.6.30, hhvm-3.18.5 - 3.22.0, 7.1.0 - 7.3.0beta1
1 0 10 : 0.11 0 10 : 0.151 0 10 : 0.21 0 10 : 0.291 0 10 : 0.31 0 10 : 0.41 0 10 : 0.51 0 10 : 0.81 0 10 : 0.991 0 10 : 0.66