For example, I have two actions:

echo '1'; // 25% что выполниться, а второе действие нет. echo '2'; // 75% что выполниться, а первое действие нет. 

How to make the actions performed randomly (in some percentage valid)?

    3 answers 3

    well, for example:

     $random = rand(1, 100); if($random <= 75) { echo 'я буду вызываться чаще'; //это действие будет выполнятся в 75% случаев } else { echo 'а я реже :('; //соответственно это в 25% } 

    In your case IMHO the most rational decision

    • Or simply: if (rand(1, 4) == 4) echo '1'; - ivkremer 6:09 pm
    • I just wrote for clarity, we don’t know what the vehicle is going to do inside these conditions, all of a sudden it will have 100,500 line logic there: D - Zowie
    • Perhaps I am mistaken, but if ($ random> = 75) should be if ($ random <= 75) - BomBom
    • No, you are not mistaken, it was sealed up, <br> <small> fixed </ small> - Zowie
    • That's right. Random from 1 to 100. The fact that he is less than 75 is a 3/4 chance, not 1/4. The only question is how random is evenly distributed at all) probably evenly. - ivkremer pm

    Then use the code

      $number = mt_rand(1,2); if ($number==1){ echo '1'; } if ($number==2){ echo '2'; } __________ 

    $number = mt_rand(1,2); - this means that we drive a random number from 1 to 2 into the $number variable and with the help of the conditions we check what value it contains, if 1 then we output 1 , if 2 then 2 , etc. If there are many such methods, use the switch and case constructs.

    • some kind of horror, condition 50 to 50 kagby written simply if-else xDDD - Zowie

    If you carefully read the course of the theory of probability, then the probability approaches its value with large numbers of repetitions, i.e. 75% probability is not 3 out of 4 or even 75 out of 100, you can safely take 7,500,000 out of 10,000,000. Now, reading the ATTENTIVE description of the rand () function and optimizing the code a little, we get:

     echo (rand(0,10000000)>7500000)?2:1; 

    something like that, and the more the number the closer the probability of distribution