Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

random

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" };
like image 439
iTayb Avatar asked May 19 '10 21:05

iTayb


4 Answers

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";
like image 84
Chad Birch Avatar answered Oct 19 '22 23:10

Chad Birch


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

like image 25
Amber Avatar answered Oct 19 '22 22:10

Amber


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.

like image 22
webbiedave Avatar answered Oct 19 '22 22:10

webbiedave


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

like image 21
Byron Whitlock Avatar answered Oct 20 '22 00:10

Byron Whitlock