How to execute one event in php based on event probability

I want something like this:

$chance = 40; //40%
if ( run the probability check script ) {
    echo "event happened"; //do the event
}
else {
   echo "event didn't happened";
}

What is the best solution to achieve something like this?

Many thanks!

+5
source share
2 answers

Use rand () :

if (rand(1,100)<=$chance)

This will return a number from 1 to 100, so the probability that it will be lower or equal to 40 is 40%.

+18
source

Umm ... Either I'm losing it, or you mean what you want below ...

$chance = 40;
if ($chance >= 40){
    echo "event happened"; //do the event
} else {
   echo "event didn't happened";
}

This suggests that the probability is equal to or greater than 40.

If you want randomness to be randomly generated, use something like $chance = rand(0,100);for a random number from 0 to 100 - then just use if statements to fulfill the conditions.

, $chance , ... , ...

0

All Articles