8

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!

1
  • Depends on "the probability check script"
    – KingCrunch
    Feb 12, 2012 at 21:09

2 Answers 2

27

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%.

1
  • 1
    What about a generic chance calculation? So $chance could = 0.1%, or 0.0001% or 1500%. Oct 10, 2013 at 6:41
0

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.