Core PHP

Rock Paper Scissors Game

This is an example PHP program that demonstrates how to program the game "Rock Papers Scissors" in PHP.

RockPaperScissors.php

<!DOCTYPE>
 <html>
  <head>
    <title>XoaX.net's PHP</title>
  </head>
  <body>
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
      <h3>Choose:</h3>
      <input type="submit" name="rock" class="button" value="Rock" />
      <input type="submit" name="paper" class="button" value="Paper" />
      <input type="submit" name="scissors" class="button" value="Scissors" />
    </form>
    <?php
      //$iYourChoice = 4;
      $iMyChoice = mt_rand(0, 2);
      if (isset($_POST['rock'])) {
        $iYourChoice = 0;
      }
      if (isset($_POST['paper'])) {
        $iYourChoice = 1;
      }
      if (isset($_POST['scissors'])) {
        $iYourChoice = 2;
      }
      if (isset($iYourChoice)) {
        echo '<br/>';
        $saNames = ['<em>rock</em>', '<em>paper</em>', '<em>scissors</em>'];
        echo '<p>Your choice is '.$saNames[$iYourChoice].' and my choice is '.$saNames[$iMyChoice].'.</p>';
        $iState = (($iYourChoice - $iMyChoice + 3) % 3);
        if ($iState == 0) {
          echo '<h3>We tied.<h3>';
        } else if ($iState == 1) {
          echo '<h3>You won!</h3>';
        } else {
          echo '<h3>I won!</h3>';
        }
      }
    ?>
  </body>
</html>
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.