Generating Random Numbers with PHP
The following script demonstrates the use of the random number function in
PHP. The script generates three random numbers and checks them against each
other to create a simple slot machine. To see this script in action click
here.
slots.php
1. The first part of this script defines the function "slotnumber()".
It then defines the variables to be used in the script "$random"
and "$slot[]". "$slot" is the variable which carries the
random numbers to be used throughout the script. The line "$random=(rand()%3);"
sets the limits for the range of numbers. In this case it will generate a
number between 0 and 3.
<HTML>
<HEAD>
<TITLE> Random Numbers </TITLE>
</HEAD>
<BODY>
<?
//define the function
function slotnumber()
{
//set variables
srand(time());
for($i=0; $i<3; $i++){
$random=(rand()%3);
$slot[]=$random;
}
|
2. The script then prints the random numbers to the screen and then compares
them. If the value of $slot[0] is equal to the value of $slot[1] AND the value
of $slot[1] is equal to the value of $slot[2], then the script will display
"Winner!--Hit refresh on your browser to play again".
//output to a table
print("<td width=\"33%\"><center>$slot[0]</td>");
print("<td width=\"33%\"><center>$slot[1]</td>");
print("<td width=\"33%\"><center>$slot[2]</td>");
//compare the numbers
if($slot[0]==$slot[1] && $slot[0]==$slot[2]){
print("</td></tr>Winner!--Hit refresh on your browser
to play again");
exit;
}
}
?>
|
3. Now to call the function. This piece of code will call for the function
to be executed.
<!--Set table
properties(this is a remark in HTML)-->
<div align="center"><center>
<table border="1" width="50%">
<tr>
<?
slotnumber();
?>
</td></tr><tr>
<td width="100%" colspan="3" bgcolor="#008080">
<form method="POST" action="slots.php">
<div align="center"><center><p><input type="submit"
value="Spin!">
</p></center></div>
</form>
</td></tr>
</table></center></div>
</BODY>
</HTML>
|
This is a simple function which could still be used for many purposes. For
example, this simple slot game could be modified further and be offered as some
sort of game to visitors. Be creative!
Other Articles:
|