In this post, I am going to write a Simple Guessing game in PHP. If you are a beginner or a college/school kid you can use this example to improve your PHP programming skill.
Here is the complete PHP code with a Simple HTML Form:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php $answer = 42; // this is the number the user has to guess // the below if condition checks if the user submmited an input if (isset($_POST['guess'])) { // take the user's input $guess = $_POST['guess']; // check if the user's input and our answer is equal or high or low if ($guess == $answer) { echo "Congratulations, you guessed the correct number!"; } elseif ($guess > $answer) { echo "Too high, try again."; } else { echo "Too low, try again."; } } ?> <html> <body> <form method="post"> <label for="guess">Guess the number:</label> <input type="text" name="guess" id="guess"> <input type="submit" value="Submit"> </form> </body> </html> |
This PHP Guessing game will take the user’s input, check it against the correct answer, and display a message depending on whether the guess is correct, too high, or too low.