tags:

views:

84

answers:

5

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" };

Thank you very much!

+3  A: 

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";
Chad Birch
For this purpose the difference between `rand()` and `mt_rand()` will very likely be unnoticeable ;-)
Joey
+1  A: 

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

Byron Whitlock
+1  A: 

Replace with

if (rand(0, 2)==2) { echo "Success"; }
baloo
+3  A: 

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

Amber
+1  A: 

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.

webbiedave