3v4l.org

run code in 300+ PHP versions simultaneously
<?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"); }

preferences:
55.42 ms | 402 KiB | 5 Q