Run a block of PHP code a certain percentage of the time

Sometimes, you may want to run code all of the time. Other times, you may want
to run code some of the time. This is how garbage collection in PHP works.
Based on your configuration for gc_probability and gc_divisor, garbage
collections runs a fraction of the time (defaulting to 1/100 or 1% of the

To do something similar to this anywhere in your code, you can generate a
random number between 1 and 100 and then see if it is less than or equal to a
value that represents the percentage of the time you want the code to run.

if (mt_rand(1, 100) <= 1) {
  // This runs 1% of the time

if (mt_rand(1, 100) <= 25) {
  // This runs 25% of the time

if (mt_rand(1, 100) <= 81) {
  // This runs 81% of the time

There will be a small bit of deviation, but it will be close enough to get the
desired results of code only running some of the time.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.