开发者

How can I randomly execute code 33% of the time in PHP?

开发者 https://www.devze.com 2022-12-31 21:22 出处:网络
I\'m not so sure how to write this: I want to generate a random number from 0 to 2, then write an if statement which executes specific code only 33% of the time.

I'm not so sure how to write this: I want to generate a random number from 0 to 2, then write an if statement which executes specific code only 33% of the time.

This is what I tried to do:

if (rand(0, 3)==开发者_运维技巧"2") { echo "Success" };


The two arguments represent the minimum and maximum random values. If you want a 1-in-3 chance, you should only allow 3 possibilities. Going from minimum 0 to maximum 3 allows 4 possible values (0,1,2,3), so that won't quite do what you want. Also, mt_rand() is a better function to use than rand().

So it'd be:

if (mt_rand(1, 3) == 2)
    echo "Success";


PHP's rand() limits are inclusive, so you'd want if(rand(0,2) == 2).


which executes specific code only 33% of the time.

Just want to point out that using random will only give the code a 33% chance of executing as opposed to running it 1/3 of the time.


Your code will execute 25% of the time. {0 1 2 3} is a set of 4 numbers. you want to do

if(rand(1,3)==2)...


Replace with

if (rand(0, 2)==2) { echo "Success"; }


I know this is a late answer, but I'd do

if(!rand(0,2))
 {
   //do stuff
 }

for any fraction 1/x desired, replace 0,2 with 0,x-1

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号