This guide will show you how to generate a random number in PHP using rand()
. There are so many reasons we might want to generate random numbers. This could be for a random sleep, a game, or adding randomness to a script.
It is important to note, that this should not be used in cases where the ability to predict the random number should not be possible. While this does generate a random number, if someone put time into it I am sure they can predict it. And if I don’t say this, there will always be the person that comments “This is not perfectly random because x,y,z”. Thats ok, but for most of our use cases, this will be more than fine. An example of where you wouldn’t want to use this?? Slot machines…
To get our random number it is simple as calling the rand()
function in php. We need to pass two parameters into the function. The first parameter is the minimum number that can be returned, and the second number is the maximum number that can be returned. Here you can see my minimum is 1
and my maximum is 100
.
# create random number
echo rand(1, 100);
After calling the function I get a random number. In this case while writing the example I got the number 56
. If I were to run it again, I would get a different number, and so on.
As you can see it is easy to generate a random number in php using the rand()
function. If you are having troubles or want to share what projects you work on that requires random numbers, please drop a comment below!