Search code examples
phpmathrandomsrand

Random Number PHP Confusion


So lets say I have 2 numbers in decimals (eg .75 and .25). I am trying to make a function that gets these 2 numbers and chooses a "winner" randomly but based on those 2 numbers' percentages. In short terms, I need the .75 number to have a better chance at getting picked then the .25 number (the .25 can still get picked, but it has only a 25% chance). How should I go about doing this?


Solution

  • $var1 = 25;
    $var2 = 75;
    $total = $var1 + $var2;
    
    $rand = mt_rand(1, $total);
    
    if($rand <= $var1)
        echo("Value one ({$var1}) Wins!");
    else
        echo("Value two ({$var2}) Wins!");
    

    Something like that should work.