How to Generate Random Number in PHP

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To use PHP to generate a random number from say 1 to 9, you use the rand() function as in …

<?php
echo rand(1,9);
?>

See example in action.

Both parameters should be integers.  And the output will be an integer.  The first parameter is the minimum number that you want generated.  And the second parameter is the maximum number that you want to generate.  Think of both the min and max values as inclusive.

If the min value is omitted, the default will be 0.  If the max value is omitted, it defaults to the largest possible random number as determined by getrandmax(), which is dependent on your operating system.

This works in PHP 4 and 5.  See PHP reference.