Random Number Functions in PHP

Author — Nitish Kumar

On This Page

PHP getrandmax() Function

PHP getrandmax() Usage

The PHP getrandmax() function will give you the maximum value that can be returned by a call to rand().

PHP getrandmax() Syntax

 getrandmax ( void ) : int

PHP getrandmax() Parameters

    This function does not accept any parameters.

    PHP getrandmax() Return Value

    The PHP getrandmax() function returns d by rand()

    PHP mt_getrandmax() Function

    PHP mt_getrandmax() Usage

    The PHP mt_getrandmax() function will give you the maximum value that can be returned by a call to mt_rand().

    PHP mt_getrandmax() Syntax

     mt_getrandmax ( void ) : int

    PHP mt_getrandmax() Parameters

      This function does not accept any parameters.

      PHP mt_getrandmax() Return Value

      The PHP mt_getrandmax() function returns the maximum random value returned by a call to mt_rand() without arguments, which is the maximum value that can be used for its max parameter without the result being scaled up (and therefore less random).

      PHP mt_getrandmax() Working Examples

      1. Calculate a random floating-point number

      <?php
      function randomFloat($min = 0, $max = 1) {
          return $min + mt_rand() / mt_getrandmax() * ($max - $min);
      }
      var_dump(randomFloat());
      var_dump(randomFloat(2, 20));
      ?>

      Output of the above code:

      float(0.91601131712832)
      float(16.511210331931)

      PHP mt_rand() Function

      PHP mt_rand() Usage

      The PHP mt_rand() function will generate a random value via the Mersenne Twister Random Number Generator.

      PHP mt_rand() Syntax

       mt_rand ( void ) : int
       mt_rand ( int $min , int $max ) : int

      PHP mt_rand() Parameters

      1. min — Optional lowest value to be returned (default: 0)

      2. max — Optional highest value to be returned (default: mt_getrandmax())

      PHP mt_rand() Return Value

      The PHP mt_rand() function returns a random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

      PHP mt_rand() Working Examples

      1. mt_rand() example

      <?php
      echo mt_rand() . "\n";
      echo mt_rand() . "\n";
      echo mt_rand(5, 15);
      ?>

      Output of the above code:

      1604716014
      1478613278
      6

      Changelog for PHP mt_rand() Function

      7.2.0 — mt_rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.

      7.1.0 — rand() has been made an alias of mt_rand().

      7.1.0 — mt_rand() has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second parameter.

      5.3.4 — Issues an E_WARNING and returns FALSE if max < min.

      Important Points about PHP mt_rand() Function

      1. This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

      2. min max range must be within the range mt_getrandmax(). i.e. (maxmin) <= mt_getrandmax() Otherwise, mt_rand() may return poorer random numbers than it should.

      Additional Tips from Fellow Developers

      Contributed By: cyrax21

      i wanted to spot out the big difference between rand and mt_rand when producing images using randomness as noise. 
       
      for example this is a comparation between rand and mt_rand on a 400x400 pixel png: http://oi43.tinypic.com/vwtppl.jpg 
       
      code: 
      
      <?php header("Content-type: image/png"); $sizex=800; $sizey=400; $img = imagecreatetruecolor($sizex,$sizey); $ink = imagecolorallocate($img,255,255,255); for($i=0;$i<$sizex/2;$i++) { for($j=0;$j<$sizey;$j++) { imagesetpixel($img, rand(1,$sizex/2), rand(1,$sizey), $ink); } } for($i=$sizex/2;$i<$sizex;$i++) { for($j=0;$j<$sizey;$j++) { imagesetpixel($img, mt_rand($sizex/2,$sizex), mt_rand(1,$sizey), $ink); } } imagepng($img); imagedestroy($img); ?>
      the differences reduce when reducing the pixels of the image.. infact for a 100x100 pixel image the noise produced from the rand function is much more realistic than how it is for a 400x400 image: http://oi39.tinypic.com/5k0row.jpg (rand is on the left, mt_rand on the right)

      PHP mt_srand() Function

      PHP mt_srand() Usage

      The PHP mt_srand() function will seeds the Mersenne Twister Random Number Generator.

      PHP mt_srand() Syntax

       mt_srand ([ int $seed [, int $mode = MT_RAND_MT19937 ]] ) : void

      PHP mt_srand() Parameters

      1. seed — An arbitrary integer seed value.

      2. mode — Use one of the following constants to specify the implementation of the algorithm to use.

      PHP mt_srand() Return Value

      The PHP mt_srand() function returns d.

      PHP mt_srand() Working Examples

      1. mt_srand() example

      <?php
      // seed with microseconds
      function make_seed()
      {
        list($usec, $sec) = explode(' ', microtime());
        return $sec + $usec * 1000000;
      }
      mt_srand(make_seed());
      $randval = mt_rand();
      ?>

      Changelog for PHP mt_srand() Function

      7.1.0 — srand() has been made an alias of mt_srand().

      7.1.0 — mt_rand() has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second parameter.

      5.2.1 — The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

      PHP rand() Function

      PHP rand() Usage

      The PHP rand() function will give you a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

      PHP rand() Syntax

       rand ( void ) : int
       rand ( int $min , int $max ) : int

      PHP rand() Parameters

      1. min — The lowest value to return (default: 0)

      2. max — The highest value to return (default: getrandmax())

      PHP rand() Return Value

      The PHP rand() function returns a pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

      PHP rand() Working Examples

      1. rand() example

      <?php
      echo rand() . "\n";
      echo rand() . "\n";
      echo rand(5, 15);
      ?>

      Output of the above code:

      7771
      22264
      11

      Changelog for PHP rand() Function

      7.2.0 — rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.

      7.1.0 — rand() has been made an alias of mt_rand().

      Important Points about PHP rand() Function

      1. This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

      2. min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax() Otherwise, rand() may return poor-quality random numbers.

      Additional Tips from Fellow Developers

      Contributed By: Anonymous

      quick way to generate randomish numbers and simple strings.
      no messing around with functions, so you can just pop the line into the middle of your existing code.
      not the most perfect for sure, but ok for plenty of situations...
      
      <?php $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string ?>
      hope someone finds it useful for somthing. regards, deeeeeen alxndr0u

      Contributed By: phpdev

      Here's an interesting note about the inferiority of the rand() function. Try, for example, the following code...
      
      <?php $r = array(0,0,0,0,0,0,0,0,0,0,0); for ($i=0;$i<1000000;$i++) { $n = rand(0,100000); if ($n<=10) { $r[$n]++; } } print_r($r); ?>
      which produces something similar to the following output (on my windows box, where RAND_MAX is 32768): Array ( [0] => 31 [1] => 0 [2] => 0 [3] => 31 [4] => 0 [5] => 0 [6] => 30 [7] => 0 [8] => 0 [9] => 31 [10] => 0 ) Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!) Now replace rand() with mt_rand() and see the difference... Array ( [0] => 8 [1] => 8 [2] => 14 [3] => 16 [4] => 9 [5] => 11 [6] => 8 [7] => 9 [8] => 7 [9] => 7 [10] => 9 ) Much more randomly distributed! Conclusion: mt_rand() is not just faster, it is a far superior algorithm.

      PHP srand() Function

      PHP srand() Usage

      The PHP srand() function will seeds the random number generator with seed or with a random value if no seed is given.

      PHP srand() Syntax

       srand ([ int $seed ] ) : void

      PHP srand() Parameters

      1. seed — An arbitrary integer seed value.

      PHP srand() Return Value

      The PHP srand() function returns d.

      PHP srand() Working Examples

      1. srand() example

      <?php
      // seed with microseconds
      function make_seed()
      {
        list($usec, $sec) = explode(' ', microtime());
        return $sec + $usec * 1000000;
      }
      srand(make_seed());
      $randval = rand();
      ?>

      Changelog for PHP srand() Function

      7.1.0 — srand() has been made an alias of mt_srand().

      Rate this post —

      Very PoorPoorAverageGoodExcellent (2 votes, average: 4.00 out of 5)
      Loading...

      Tags: |

      Subscribe
      Notify of
      guest
      0 Comments
      Oldest
      Newest Most Voted
      Inline Feedbacks
      View all comments
      0%