Generating random numbers may not seem obviously useful, but, as your programs become increasingly complicated, you’ll see this is actually a common task—for example to randomize data for testing.
rand() function returns a random integer. We have some flexibility with how we invoke it. Invoking
rand() with no arguments will return a number between 0 and the largest number our current environment will allow; this is a quirk of PHP. We can find out what this number is by invoking a different built-in function,
$max = getrandmax(); echo $max; echo rand(); // Prints a number between 0 and $max
In the code above, we assigned the largest possible random integer to the
$max variable by invoking the
Next, we used
echo to print a random integer. This integer will be a number between 0 and
Functions often have a strict definition which dictates exactly which arguments it expects to be called with and results in an error otherwise. The
rand() function, however is somewhat flexible.
If we’d like more control over the random number we generate, we can invoke the
rand() function with two integer arguments representing the smallest allowable random number and the largest allowable random number. Fun fact: the second argument provided can be larger than
getrandmax(). These numbers are inclusive meaning the arguments we pass in could be generated by the function.
echo rand(1, 2); // Prints either 1 or 2 echo rand(5, 10); // Prints a number between 5 and 10 (inclusive!) echo rand(1, 100); // Prints a number between 1 and 100 (inclusive!)
Ok let’s get random!
getrandmax() to find out what the maximum random number is in this environment.
Now that we know its bounds. Let’s see what we get when we invoke the
echo to print an invocation of the
It’s totally optional, but you might consider adding this line of code between your other
echo statements so you can read the output more easily:
Ok! Let’s call
rand() again. This time use
rand() to print a random number between 1 and 52 (both inclusive).