How to Generate a Random Number in PHP


php


To generate a random number in PHP, we use the mt_rand function.

The general form to generate a random number is:

$random_number= mt_rand(minimum_number_range, maximum_number_range);

where
minimum_number_range is the minimum number value that the mt_rand function can generate
maximum_number_range is the maximum number value that the mt_rand function can generate

The $random_number variable stores the random number which you generate from the mt_rand() function.

For example, if you want to generate a random number from 50 to 70, the minimum number range would be 50 and the maximum number range would be 70, because you want to generate a random number between 50 and 70.

Example

To generate and display a number from 1 to 100, the code to do this is:

$random_number= mt_rand(1, 100);
echo $random_number;

Actual PHP Output

Refresh this page to see a new generated random number:

93


HTML Comment Box is loading comments...