In this post, we are going to see how to print Random numbers in PHP. It is very simple in PHP because it has an in-build function called rand($min, $max) that does the job. Let me show you a simple example first.
First example program we are going to see is “How to print random numbers between 1 and 100 in PHP”:
1 2 3 4 5 6 7 |
<?php // Random numbers between 0 and 100 $rand_num = rand(0, 100); print $rand_num; ?> |
As I said before, we have an in-build function called rand($mix, $max) which accepts two parameters, min and max value. So just giving the min & max values in the first & second parameters does the job. And for every refresh, it is going to give a random value between these two.
Now, let’s write another example for the same rand($mix, $max) function where you can give the min and max value dynamically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Print a Random number between values in PHP</title> </head> <body> <h3>Print a Random number between values in PHP</h3> <form action="" method="post"> Min: <input type="number" name="min" min="0" value="1" /><br /><br /> Max: <input type="number" name="max" min="1" value="100" /><br /><br /> <input type="submit" /><br /><br /> </form> </body> </html> <?php //after hit the enter button //form method="post" so we have to use $_POST if($_POST){ //get the value from input field $min = $_POST['min']; $max = $_POST['max']; //Random numbers between 0 and 100 $rand_num = rand($min, $max); print "<h2>Random number between $min & $max is ".$rand_num."</h2>"; } ?> |
In the above example, we are using an HTML form to get the min & max values from the user, then using PHP we are capturing the values and passing it to function rand($mix, $max) to generate a random number.
I hope this gives a clear picture of how to generate a Random number between two values in PHP.
You can actually see the demo for the same in here, just click the below button to see it.