How to Generate a Random Number with PHP

Josh Sherman
1 min read
Software Development PHP

Generating a random number in PHP is very simple and like most things, can be done a number of different ways. The old standby is to use the function rand() to to generate a random integer between the minimum and maximum values that you provide. To generate a number between 1 and 100 you would do this:

$random = rand(1, 100);

At this point, rand() basically exists for backwards compatibility’s sake. The newer / preferred function to use is mt_rand() which addresses speed concerns with the former and clocks in at 4 times faster. The “MT” in the name referred to Mersenne Twister which is an alternative random number generator to libcs. You use this function in the same way:

$random = mt_rand(1, 100);

This is great for generating random integers, but what if you want a random decimal value? There’s actually not a function to do so, but you could easily divide a random number by a larger number or slap a decimal at the beginning of the value to achieve the desired results.

On a side note, as of PHP 4.2.0 you no longer need to concern yourself with seeding the random number generator (hence why it wasn’t mentioned here ;)

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. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles