Jump to content

php rand and percentage


Recommended Posts



I basically want a function that takes a parameter which is a percentage chance of the functioning returning true.

A user can move from tier 1->10 and at tier 1 there's a 70% chance to move to tier 2, from tier 2 there's a slightly less chance to move up, and so on.


I tried with the following piece of code:



public function rollTheDice($winnerPercentage)
$number = rand(1, 100);
if ($number <= $winnerPercentage)
return true;
return false;


The above code makes logical sense to me:

1. Pick a random number between 1 and 100.

2. If that number is less than or equal to the percentage, then we passed (example, if the random number is less than or equal to 70.. there must be a 70% chance of this?)


This however does not seem to work, in fact it appears that when simulating a roll, 70% fails at the very first step (where there is a 70% chance of winning..)

To actually make it to tier 10, has yet to be accomplished, so by simulating this with unlimited attempts for 120 seconds straight doesn't seem to "win".


I tried (just for fun) and change the if-statement so:

if ($number >$winnerPercentage)


This seems to be working quite well, as the simulator quickly reaches tier 10 this way.

Any suggestions to code changes, or can someone explain why it is working way better when exchanging less than with greater than?

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.