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

Josh Sherman
1 min read
Software Development PHP

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

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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles