Convert interest to cumulative probability, then compare them with a random number.
If a random number falls into the category, displays the result. If not, go to the next until you find it. This allows you to derive a number based on the percentage probability specified in the array.
$percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); $random = mt_rand(0,10000)/100; foreach ($percentage as $key => $value) { $accumulate += $value; if ($random <= $accumulate) { echo $key; break; } }
source share