Skip to content

rand()

Today, we will discuss the rand() function in PHP, which generates a random integer.

What is the rand() Function?

The rand() function is a built-in PHP function that returns a random integer within a specified range. Both arguments are optional: if omitted, the function defaults to a range between 0 and getrandmax().

How to Use the rand() Function

Using the rand() function in PHP is straightforward. Here is an example:

How to Use the rand() Function in PHP?

php
<?php
// Generate a random integer between 1 and 10
// Note: Both arguments are optional. Defaults to 0 and getrandmax()
$result = rand(1, 10);

// Output the result
echo $result;
?>

In this example, we call the rand() function to generate a random integer between 1 and 10. We then store the result in a variable and output it to the screen. For better randomness and performance, PHP recommends using mt_rand() as a modern alternative.

Conclusion

The rand() function is a useful tool for generating random integers within a specific range. By understanding its optional parameters and default behavior, you can easily integrate it into your PHP applications. We hope this guide helps you use rand() effectively in your code.

Practice

What does the rand() function in PHP do?

Dual-run preview — compare with live Symfony routes.