Generate a random number in PHP

In this post we will see how to generate a random number in PHP in a simple way using two different methods: rand and mt_rand. This way we will learn in a simpler way to manage numbers in PHP.

PHP makes it easier for us to obtain random numbers with the function rand(), which receives a pair of values, the minimum and maximum of the random numbers to be generated. In this demo we are going to obtain a random number between 1 and 30, including these two values ​​among the possible ones, if nothing is indicated at rand(), the minimum value will be zero.

The maximum value depends on the platform it is running on PHP, for example in Windows the maximum value would be 32786. If we want to ensure that this maximum value is greater, then it is convenient to define the maximum and minimum values ​​when calling the function.

Now let’s look at the code:

<?php
  $d=rand(1,30);
  echo $d ;
?>

With this simple pair of lines we can obtain a random number. We can also obtain a random number with the function mt_rand() which is much better than rand() since it is much faster and has a better algorithm for obtaining random numbers.

<?php
  $d=mt_rand(1.30);
  echo $d ;
?>

With these functions we can generate a random number in PHP easily and quickly.

Leave a Comment