Generate Random Numbers in PHP

To create random numbers in PHP, you can use the rand() function call, which takes either zero or, optionally, two parameters determining the minimum and maximum random numbers (inclusive) that you’d like. If you don’t specify a maximum then it will default to a value, RAND_MAX, set in the PHP configuration. The function returns an integer, generated “randomly.” (Computers can’t generate real random numbers, but this tries and is suitable for most purposes.)

You can get the value of RAND_MAX with the function getrandmax(). Then if you desire a random number larger than that, you have to specify the min and max bounds as parameters, eg rand(0, 100000) will return a random number between 0 and 100000 inclusive - so both 0 and 100000 can be returned.

For example:

<?php // random number between 0 and RAND_MAX:
  echo rand(); // output: 28688 (for example)
  // random number between 37 and 50:
  echo rand(37, 50); // output: 44
  // find out the value of RAND_MAX:
  echo getrandmax(); // output: 32767
  // get a larger random number by specifying min and max:
  echo rand(0, 1000000); // output: 351990

The output shown in the comments above is as an example. Since it is generating random numbers, the numbers generated are very likely to be be different every time.



The latest posts sent straight to your inbox.