Random Numbers

You want to generate a random numberwithin a range of numbers.

PHP has two different random number generators:

For a version of PHP earlier than 4.2, you need to seed the generator by calling srand() or mt_srand() before using rand() or mt_rand(). The seed is a number the randopm function uses as the basis for generating the random numbers it returns.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Random Numbers</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$lower = 1;
$upper = 100;

echo "The random number between $lower and $upper using rand() is: ", rand($lower, $upper), "<br />";
echo "The random number between $lower and $upper using mt_rand() is: ", mt_rand($lower, $upper), "<br />";

echo "The random number between $lower and $upper using rand() is: ", rand($lower, $upper), "<br />";
echo "The random number between $lower and $upper using mt_rand() is: ", mt_rand($lower, $upper), "<br />";

echo "<p>seed the generator first.</p>";
srand();
echo "The random number between $lower and $upper using rand() is: ", rand($lower, $upper), "<br />";
mt_srand();
echo "The random number between $lower and $upper using mt_rand() is: ", mt_rand($lower, $upper), "<br />";

?>
</p>
</body>
</html>

View the effect


Numbers | Introduction | Checking a Valid Number | Comparing FLoating-Point Numbers | Rounding FLoating-Point Numbers | Series of Integers | Random Numbers | Logarithms | Exponents | Formatting Numbers | Formatting Monetary Values | Printing Correct Plurals | Trigonometric Functions | Converting Between Bases
© 2008: Hann So
email: hso@voyager.deanza.edu