## PHP random number generator

``````
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!--
An example of using a (pseudo)random number generator
Author: Elena Machkasova elenam@morris.umn.edu
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>
Random number generator in php
</title>
<body>
<h2>(Pseudo)random number generator in php</h2>
<p>
Function rand() gives a random integer between 0 and the largest possible
integer. If you give the function a range of random numbers you want, it
returns an integer in that range. For instance, rand(5, 15) returns
an integer between 5 and 15 (inclusive). The result has an equal
probability to be any number within the range (i.e. it's a uniform
distribution). A new number is generated every time you use the function.
</p>
<p>
The numbers are not really random, the function is actually deterministic.
That's why the correct name for such functions is "pseudo-random number
generator".
It uses the current system time (up to nanoseconds) as the "seed" so that
number sequences come out different every time.
</p>
<p>
<?php
// note that calling a function within a quoted string doesn't
// work. Use string concatenation (the dot) for a function call
print "rand() = ".rand()."<br />\n";

print "rand(1, 10) = ".rand(1, 10)."<br />\n";

print "Another call to rand(1, 10) = ".rand(1, 10)."<br />\n";
?>
</p>
<p>
You can store a random number in a variable:
</p>
<p>
<?php
\$r = rand(2, 5);

print "\\$r = \$r <br />\n";
?>
</p>
<p>
You can store a random number in a variable:
</p>
<p>
<?php
\$r = rand(2, 5);

print "\\$r = \$r <br />\n";
?>
</p>
</body>
</html>
``````

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.