Artur Mendes
Artur Mendes

Reputation: 127

How do i execute one event in php based on a probability for the event to happen

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 that?

thanks a lot!

Upvotes: 9

Views: 6570

Answers (2)

MrJ
MrJ

Reputation: 1938

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

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

This assumes that the chance is equal to or is more than 40.

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

At the end of the day it depends if your initial $chance is a fixed number or it is random or occurs as a result of a calculation.... unfortunately you haven't provided much insight...

Upvotes: -1

dorsh
dorsh

Reputation: 24730

Use rand():

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

This will return a number between 1 and 100, so that the probability of it being lower or equal to 40 is 40%.

Upvotes: 28

Related Questions