How to generate a random integer value between min and max in PHP

4 Answers

0 votes
echo rand(1, 10) . "\n";
echo rand(1, 10) . "\n";
echo rand(1, 10) . "\n";
 
 
 
/*
run:
 
4
3
9
 
*/

 



answered Aug 19, 2015 by avibootz
edited Apr 14, 2024 by avibootz
0 votes
$min = 30;
$max = 40;
 
for ($i = 0; $i < 25; $i++) {
     echo rand($min, $max) . "\n";
}


 
/*
run:
 
31
36
30
32
33
33
30
33
40
35
32
32
33
31
35
33
39
38
32
30
30
35
37
34
32
  
*/

 



answered Nov 20, 2015 by avibootz
edited Apr 14, 2024 by avibootz
0 votes
$minimum = 8;
$maximum = 19;

// From version 7.1.0 rand() has been made an alias of mt_rand()

echo mt_rand($minimum, $maximum) . "\n";
echo mt_rand($minimum, $maximum) . "\n";
echo mt_rand($minimum, $maximum) . "\n";
echo mt_rand($minimum, $maximum) . "\n";
echo mt_rand($minimum, $maximum) . "\n";


 
/*
run:
 
18
16
17
12
11
  
*/

 



answered Apr 14, 2024 by avibootz
0 votes
$min = 14;
$max = 25;
  
for ($i = 0; $i < 10; $i++) {
    // generates a cryptographically secure random integer
    $randomNumber = random_int($min, $max);
    echo $randomNumber . "\n";
}


/*
run:

16
17
23
22
17
21
25
14
23
25

*/

 



answered Sep 15, 2024 by avibootz
...