PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I'm working on a WordPress plugin and I only want it to show once in a great long while. It's a popup message at the bottom of the screen. Will this work?
$r=rand(1,100);
if ($r != 44)
{
die();
}
Basically, I'm making a random number, if the random number is not equal to 44 (it could be any number between 1 and 100) then it kills the script. I could test it, but it has a 3 second delay, and 1 in 100 chances are pretty hard to come by.
narcah wrote:and 1 in 100 chances are pretty hard to come by
Since the number is being picked randomly and not in any sequence you can't say that the time taken before 44 is reached is fixed. A timer will be a better option if you are looking for a action to occur after a certain time.
You can test this for yourself by running a for loop x amount of times to see the results;
social_experiment wrote:Results of running the script twice; 44 will pop up more unexpectedly than you wish
And that there touches on the difference between randomness and infrequency. Random is random: it's possible (though unlikely) that 44 will come up twice in a row. The first roll has nothing to do with the second. If that shouldn't happen then simply "random" isn't enough and there'd have to be a second criteria or rule in the mix.
For instance, "randomly... but always within 100 minutes of the last time". This is pretty easy to do with
(rand() / getrandmax()) <= (time elapsed since the last time it happened / 100 minutes)
Or there's "randomly... within the next 100 instances", which basically means picking a random number X between 1 and 100 and waiting for the Xth instance.