Skip to content

Instantly share code, notes, and snippets.

@IronGhost63
Last active June 23, 2022 22:02
Show Gist options
  • Save IronGhost63/3ece8f6ab145edd257326011bac129f4 to your computer and use it in GitHub Desktop.
Save IronGhost63/3ece8f6ab145edd257326011bac129f4 to your computer and use it in GitHub Desktop.
Random choices with weight adjustable
<?php
// define options with chance weight
$choices = [
'a' => 10.50,
'b' => 30,
'c' => 24.50,
'd' => 35,
];
$total = array_sum( $choices ); // total chance
$percent = rand( 0, $total*100 ) / 100; // random chance with decimal point
$award = null;
$carry = 0;
// loop through each option
foreach ( $choices as $key => $value ) {
// calculate for floor/ceil value for current option
$high = $carry + $value;
$low = $carry;
// check if randomized $percent inside the threshold
if ( $percent > $low && $percent <= $high ) {
$award = $key;
// value inside the threshold, break loop.
break;
}
// value outside the threshold, save next low value and continue.
$carry += $value;
}
// output
echo "percent: {$percent}\n";
echo "award: {$award}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment