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)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With