web-dev-qa-db-fra.com

Nombre aléatoire compris entre [min - max] avec PHP

Existe-t-il un moyen de générer un nombre aléatoire basé sur un minimum et un maximum?

Par exemple, si min était 1 et max 20, il devrait générer un nombre compris entre 1 et 20, y compris 1 et 20?

78
Val
<?php
  $min=1;
  $max=20;
  echo Rand($min,$max);
?>
132
Prisoner

Dans un nouveau PHP7 , il existe enfin un support pour un entiers pseudo-aléatoires cryptographiquement sécurisés.

int random_int ( int $min , int $max )

random_int - Génère des entiers pseudo-aléatoires sécurisés de manière cryptographique

ce qui rend les réponses précédentes obsolètes.

29
Salvador Dali

UNE plus rapide Une version plus rapide utiliserait mt_Rand:

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

Source: http://www.php.net/manual/en/function.mt-Rand.php .

REMARQUE: Votre serveur doit avoir le module Math PHP activé pour que cela fonctionne. Dans le cas contraire, boguez votre hôte pour l’activer, ou vous devez utiliser le Rand () normal (et plus lent).

17
Matt Cromwell
(Rand() % ($max-$min)) + $min

ou

Rand ( $min , $max )

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

5
pinkfloydx33

J'ai regroupé les réponses ici et ai rendu la version indépendante;

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
}
4
vonUbisch
Rand(1,20)

Les documents pour la fonction Rand de PHP sont ici:

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

Utilisez la fonction srand() pour définir la valeur de départ du générateur de nombres aléatoires.

4
winwaed

Essaye celui-là. Il générera un identifiant selon votre souhait.

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;
}
0
asi_x