Random Number Functions in PHP

getrandmax() — Show largest possible random value

mt_getrandmax() — Show largest possible random value

mt_rand() — Generate a random value via the Mersenne Twister Random Number Generator

mt_srand() — Seeds the Mersenne Twister Random Number Generator

rand() — Generate a random integer

srand() — Seed the random number generator

PHP getrandmax() Function

What does getrandmax() do?

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

    What does mt_getrandmax() do?

    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

      What does mt_rand() do?

      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

      What does mt_srand() do?

      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

      What does rand() do?

      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. (maxmin) <= 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

      PHP srand() Function

      What does srand() do?

      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().

      Additional Tips from Fellow Developers

      Contributed By: Niels Keurentjes

      Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.

      Rate this post —

      Very PoorPoorAverageGoodExcellent (1 votes, average: 5.00 out of 5)
      Loading...

      Author: Nitish Kumar

      Leave a Reply

      avatar
      1000
        Subscribe  
      Notify of
      0%