1. Home
  2. Computing & Technology
  3. PHP / MySQL

Flip a Coin With PHP
Can't make a decision? Flip a coin... with PHP

By , About.com Guide

This code teaches you how to flip a coin with PHP. It is done by assigning numbers to heads and tails. In our example we use the rand () function to choose either the number one or two. If it chooses one, we echo the HEADS entry, and if it chooses two we tell the user their TAILS entry. If you wanted to make it look even more like a coin toss, you could link an image of a coin head or tail instead of just echoing the words "heads" and "tails."
<html>
<head><title>Coin Toss</title></head>
<body>

<?
//Retreives the values the user enters for heads and tails
$heads = $_POST["heads"];
$tails = $_POST["tails"];

//Only replies if they have entered text
If ($heads)
{
Echo "<h2>Answer</h2><p> ";
//Chooses a random number
$result = Rand (1,2);

//Based on the random number, gives an answer
if ($result ==1)
{
Echo "HEADS<br> $heads";
}

if ($result ==2)
{
Echo "TAILS<br> $tails";
}
}
?>

< !-- HTML form to collect coin data -->
<h2>Coin Toss</h2><p>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<p>
If it's heads:<input type="text" name="heads" /> <br>
If it's tails:<input type="text" name="tails" /> <br>
<input type = "submit" name = "FLIP"/>
</form>
</body>
</html>
More PHP / MySQL Quick Tips
Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Step By Steps
  5. PHP Coin Toss - Yes or No with PHP - Flip a Coin with PHP

©2009 About.com, a part of The New York Times Company.

All rights reserved.