1. Computing

Discuss in my forum

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> 
Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Computing
  3. PHP / MySQL
  4. Step By Steps
  5. PHP Coin Toss - Yes or No with PHP - Flip a Coin with PHP

©2013 About.com. All rights reserved.