Random number in range [min - max] using PHP

PhpSecurityRandom

Php Problem Overview


Is there a way to generate a random number based on a min and max?

For example, if min was 1 and max 20 it should generate any number between 1 and 20, including 1 and 20?

Php Solutions


Solution 1 - Php

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

Solution 2 - Php

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

> random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

Solution 3 - Php

A quicker faster version would use mt_rand:

$min=1;
$max=20;
echo mt_rand($min,$max);

Source: <http://www.php.net/manual/en/function.mt-rand.php>;.

NOTE: Your server needs to have the Math PHP module enabled for this to work. If it doesn't, bug your host to enable it, or you have to use the normal (and slower) rand().

Solution 4 - Php

I have bundled the answers here and made it version independent;

function generateRandom($min = 1, $max = 20) {
    if (function_exists('random_int')):
        return random_int($min, $max); // more secure
    elseif (function_exists('mt_rand')):
        return mt_rand($min, $max); // faster
    endif;
    return rand($min, $max); // old
}

Solution 5 - Php

(rand() % ($max-$min)) + $min

or

rand ( $min , $max )

http://php.net/manual/en/function.rand.php

Solution 6 - Php

rand(1,20)

Docs for PHP's rand function are here:

http://php.net/manual/en/function.rand.php

Use the srand() function to set the random number generator's seed value.

Solution 7 - Php

Try This one. It will generate id according to your wish.

function id()
{
 // add limit
$id_length = 20;

// add any character / digit
$alfa = "abcdefghijklmnopqrstuvwxyz1234567890";
$token = "";
for($i = 1; $i < $id_length; $i ++) {
 
  // generate randomly within given character/digits
  @$token .= $alfa[rand(1, strlen($alfa))];

}    
return $token;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionValView Question on Stackoverflow
Solution 1 - PhpPrisonerView Answer on Stackoverflow
Solution 2 - PhpSalvador DaliView Answer on Stackoverflow
Solution 3 - PhpMatt CromwellView Answer on Stackoverflow
Solution 4 - PhpvonUbischView Answer on Stackoverflow
Solution 5 - Phppinkfloydx33View Answer on Stackoverflow
Solution 6 - PhpwinwaedView Answer on Stackoverflow
Solution 7 - Phpasi_xView Answer on Stackoverflow