How to optimize if else in post method? - php

I have mainly two question first describe what I going to do. I've created some animal in the code by saying that octopus will have 8 leggs,9 brain,1 stomach,3 heart similarly for other property.And by a html form using post method I'm taking input from user as showing the animals image if the description matches.
I've also declared the corresponding animals name.I want to also show the name of the animal after matching(by printing $name).
2)Here I'm matching user input for each animal(by using if,elseif elseif) but how can I optimize so that if there is more than 100 animal I don't have to do 100 else if.
Here is my code.
<?php
class animal{
var $name;
var $brain;
var $stomach;
public $heart;
public $leg;
function __construct($aBrain, $aStomach, $aHeart, $aLeg)
{
$this->brain = $aBrain;
$this->stomach = $aStomach;
$this->heart = $aHeart;
$this->setLeg($aLeg);
}
function isBipedal(){
if ($this->leg == 2) {
return "it is a bipedal animal";
}else {
return "it is not a bipedal animal";
}
}
function getLeg(){
return $this->leg;
}
function setLeg($leg){
if ($leg == 8 ||$leg == 4 ||$leg == 2) {
$this->leg= $leg;
}else {
$this->leg= "non-pedal";
}
}
}
$octopus = new animal(9,1,3,8);
$cow = new animal(1,4,1,4);
$human = new animal(1,1,1,2);
$octopus->setLeg(8);
//echo "new leg ".$octopus->leg = 0;
echo "<br>".$octopus->getleg();
echo "<br>".$human->isBipedal(). "<br>";
if(isset($_POST['submit'])) {
if(isset($_POST['brain'])
&& isset($_POST['stomach'])
&& isset($_POST['heart'])
&& isset($_POST['leg']) ){
$myBrain = $_POST['brain'];
$myStomach = $_POST['stomach'];
$myHeart = $_POST['heart'];
$myLeg = $_POST['leg'];
// echo "brain = ". $myBrain. "<br>";
// echo "stomach = ". $myStomach. "<br>";
// echo "heart = ". $myHeart. "<br>";
// echo "leg = ". $myLeg. "<br>";
if($myBrain==$octopus->brain
&& $myStomach==$octopus->stomach
&& $myHeart==$octopus->heart
&& $myLeg==$octopus->leg
){
?>
<div class="animal-info">
<div><p class="blinking">You are Octopus</p></div>
<img src="media/octopus.jpg" alt="" class="animal-img">
<img src="media/octopus.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$cow->brain
&& $myStomach==$cow->stomach
&& $myHeart==$cow->heart
&& $myLeg==$cow->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Cow</span>
</div>
<img src="media/cow.jpg" alt="" class="animal-img">
<img src="media/cow.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$human->brain
&& $myStomach==$human->stomach
&& $myHeart==$human->heart
&& $myLeg==$human->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Human</span>
</div>
<img src="media/human.jpg" alt="" class="animal-img">
<img src="media/human.gif" alt="" class="animal-img">
</div>
<?php
}else{
echo "you don't match with anything at all";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post">
<span>How many brain you have?</span>
<input type="text" name="brain" id="brain">
<br>
<span>How many stomach you have?</span>
<input type="text" name="stomach" id="stomach">
<br>
<span>How many heart you have?</span>
<input type="text" name="heart" id="heart">
<br>
<span>How many leg you have?</span>
<input type="text" name="leg" id="leg">
<br>
<input type="submit" name="submit" value="Let me see">
</form>
</body>
</html>

u should either store them in a DB and make a query, or store them in array and search by some linq equivalent in php

Could You try with a Switch case?
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>

Related

Input and output values for php into the browser?

I just started my module on php for school, having completed Javascript two months ago I am familiar with a lot of the elements but a bit rusty. Basically I setup a form with html and added a bit of css to make it pretty. The school is making us do some generic exercices. I now how to grab values etc using this with Javascript
document.getElementById("textBox").value;
and to return the output through my div I created with
document.getElementById("return").innerHTML = ... ;
I honestly can't figure out how to do this with php and I am sure it's real easy but can't for the life of me find a solution online and the schools videos are very vague.
The exerciser is "Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number"
This is the code I have so far....
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>PHP exercise 1</title>
<link rel="stylesheet" type="text/css" href="./styling1.css"/>
</head>
<body>
<!--E X C E R S I S E 3 !-->
<section id="allContent">
<section>
<button class="hide" id="clic"> <h4> E X E R C I C E 1 </h4></button>
</section>
<div id="container" class="hidden">
<div id="Barbox"><p class="pClass"> Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number</p>
</div>
<div id="background"></div>
<div class="ball"></div><div id="ball2"></div>
<div id="titleBox">
<p id="titlePRG">Enter a number!</p>
</div>
<form>
<input type="text" value="<?php echo $number = 1 ; ?>" id="textField">
<input type="button" value="Enter" class="button" onclick="return_day()">
</form>
<div id="valueReturned">
<p id="returnText"><p>
</div>
<h3> Next Exercise </h3>
</div>
</section>
<?php
function return_day(){
$number = 1 ;
if ($number == 1){
echo "The day of the week is Monday";
}
else if ($number == 2){
echo "The day of the week is Tuesday";
}
else if ($number == 3){
echo "The day of the week is Wednesday";
}
else if ($number == 4){
echo "The day of the week is Thursday";
}
else if ($number == 5){
echo "The day of the week is Friday";
}
else if ($number == 6){
echo "The day of the week is Saturday";
}
else if ($number == 7){
echo "The day of the week is Sunday";
}
else{
echo ("Wrong input, try again!");
}
}//end of function
?>
This is what the browser looks like if it makes any difference so you understand my question
The answer is supposed to display in the white box at the bottom which is
Unlike Javascript, php is totally different! Javascript's functions can be accessed in HTML by using onclick, onload, etc. attributes, but php's functions are quite different and can only be accessed through php codes. First you need to create a prom with a method and then send to the same page(in your case) and then run the conditions that you have applied and at last echo the result as i have done in it.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<title>PHP exercise 1</title>
<link rel="stylesheet" type="text/css" href="./styling1.css" />
</head>
<body>
<!--E X C E R S I S E 3 !-->
<section id="allContent">
<section>
<button class="hide" id="clic">
<h4> E X E R C I C E 1 </h4>
</button>
</section>
<div id="container" class="hidden">
<div id="Barbox">
<p class="pClass"> Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number</p>
</div>
<div id="background"></div>
<div class="ball"></div>
<div id="ball2"></div>
<div id="titleBox">
<p id="titlePRG">Enter a number!</p>
</div>
<form method="get" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="text" value="" id="textField" name="number">
<input type="submit" value="Enter" class="button" name="submit">
</form>
<?php
if (isset($_GET['submit']))
$number = isset($_GET['number']) ? $_GET['number'] : '';
if ($number == 1) {
$returntext = "The day of the week is Monday";
} else if ($number == 2) {
$returntext = "The day of the week is Tuesday";
} else if ($number == 3) {
$returntext = "The day of the week is Wednesday";
} else if ($number == 4) {
$returntext = "The day of the week is Thursday";
} else if ($number == 5) {
$returntext = "The day of the week is Friday";
} else if ($number == 6) {
$returntext = "The day of the week is Saturday";
} else if ($number == 7) {
$returntext = "The day of the week is Sunday";
} else {
$returntext = ("Wrong input, try again!");
}
?>
<div id="valueReturned">
<p id="returnText"><?php echo $returntext; ?><p>
</div>
<a href="index4.html" id="jButton">
<h3> Next Exercise </h3>
</a>
</div></section>
Hope that, you must be running these php codes in a suitable server! Good go!
Below code should help you understand.
<?php
$response = "";
if(isset($_POST) && isset($_POST["mytext"])): /// check if user submitted form
$num = $_POST["mytext"]; //put form mytext variable.. retrieved from html <input name="mytext"....
if(is_numeric($num)):
switch($num):
case "1":
$response = "Monday";
break;
case "2":
$response = "Tuesday";
break;
case "3":
$response = "Wednesday";
break;
case "4":
$response = "Thursday";
break;
case "5":
$response = "Friday";
break;
case "6":
$response = "Saturday";
break;
case "7":
$response = "Sunday";
break;
default:
$response = "Invalid number";
endswitch;
else:
$response = "Invalid number";
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PhpFiddle Initial Code</title>
<!--
http://phpfiddle.org
-->
<script type="text/javascript">
</script>
<style type="text/css">
</style>
</head>
<body>
<div style="margin: 30px 10%;">
<h3>My form</h3>
<form id="myform" name="myform" action="" method="post">
<label>Text</label> <input type="text" value="" size="30" maxlength="100" name="mytext" id="" /><br /><br />
<br />
<button id="mysubmit" type="submit">Submit</button><br /><br />
<?php if (isset($_POST)): ?>
<div style="background-color:red;color:white;"><?php echo $response; ?></div>
<?php endif; ?>
</div>
</form>
</div>
<?php
?>
</body>
</html>

PHP Quiz not working properly

I'm trying to make a simple php quiz,but instead of choices I have to insert answers and compare them with strcasecmp() so it won't be a problem if the first letter is uppercase or anything like that,but the code doesn't work properly.Sometimes it doesn't return the correct result,even though I insert the correct answer.
Here is the code:
<?php
$number = rand(1,2);
$result = "";
$answer = "";
$question = "";
$question1 = "What is the capital of China";
$question2 = "What king of country is China?";
$answer1 = "beijing";
$answer2 = "republic";
if ($number == 1) {
$answer = $answer1;
$question = $question1;
}
if ($number == 2) {
$answer = $answer2;
$question = $question2;
}
if(isset($_POST['submit'])){
if (strcasecmp($answer,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Wrong!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="index.php">
<div class="middle">
<p class="question"><?php echo $question;
?></p>
<p class="result"><?php echo $result;
$result = "" ?></p>
<div class="box">
<input type="text" name="answer" placeholder="Type here" class="text">
</div>
</div>
<input type="submit" name="submit" value="Continue" class="btn">
</form>
</body>
</html>
By looking at your code, we can see that when you submit your form, you are restarting the script, which actually resets $random to a new value. With 2 questions, you have 50% chances to have the 'correct' answer, but you would see that your script doesn't work at all with more questions added.
Basically, you should use another way to achieve what you want. You could try to add the id of the question in an hidden <input> and check when your form is submit to determine which one it was.
if(isset($_POST['submit'])){
switch ($_POST['question']) { // Add '{'
case 1:
if (strcasecmp($answer1,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
}
break;
case 2:
if (strcasecmp($answer2,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
} // Forgot to Add '}'
break;
} // Add '}' It give error in PHP 5.3 Parse error: syntax error, unexpected T_CASE, expecting ':' or '{'
}
For the HTML, you could add this input in your form :
<input type="text" name="question" value="<?php echo $number ?>" hidden>
This is not the best way to achieve what you want, this is just an example of what would work.

Counter not increasing more than one time

I wanted to make specific letter counter, but my counter is not increasing more that once. Can some one explain what i'm doing wrong?
Here is my code:
PHP:
<?php
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
$count_v++;
case 's':
$count_s++;
}
}
}
?>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form action="index.php" method="POST">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': ".$count_v."<br/>";
echo "Count of letter 'S': ".$count_s."<br/>";
?>
</div>
</body>
</html>
Try this it will be work perfectly. paste it in any test file. This will retain no of times you input v and no of times you input s, value of s and v will remain same of input some other value.
<?php
$input = '';
if(!isset($count_v))
{
$count_v=0;
}
if(!isset($count_s))
{
$count_s=0;
}
if (filter_has_var(INPUT_POST, 'submit'))
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$input = $_POST['inp'];
switch ($input)
{
case 'v':
$_POST['count_v']++;
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
case 's':
$count_v=$_POST['count_v'];
$_POST['count_s']++;
$count_s=$_POST['count_s'];
break;
default:
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form method="POST">
<input type="hidden" name='count_v' value="<?php echo $count_v?>">
<input type="hidden" name='count_s' value="<?php echo $count_s?>">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': " . $count_v . "<br/>";
echo "Count of letter 'S': " . $count_s . "<br/>";
?>
</div>
</body>
</html>
you need to store counters in each request, because the variables lifetime is short (request life time), then they will be re-init from 0
to do this you can store the counters in file, database, or session
it depends on the time you want them to persist.
below is a sample for using session
** note the new line session_start(); you need to add it.
<?php
session_start();
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
if(!isset($_SESSION["count_v"])){
$_SESSION["count_v"] = 0;
}
$tmp = $_SESSION["count_v"];
$tmp++;
$_SESSION["count_v"] = $tmp;
break;
case 's':
if(!isset($_SESSION["count_s"])){
$_SESSION["count_s"] = 0;
}
$tmp = $_SESSION["count_s"];
$tmp++;
$_SESSION["count_s"] = $tmp;
break;
}
}
}
?>
and to read the values (in html page) use this:
<?php
echo "Count of letter 'V': ".$_SESSION["count_v"]."<br/>";
echo "Count of letter 'S': ".$_SESSION["count_s"]."<br/>";
?>
if you are going to store more than the 2 letters (s and v) then you can make the session key "count_v" generated dynamically using input itself. this will be a much less code, you will not need a switch/case
Edit: as i saw in your comment above, yes you can maintain counter values using hidden fields in HTML page, and use them to initialize the $count_s and $count_v instead of zero. you need to take care of first request when hidden values might be unset, or they could be zero

SongOrganzier Isnt Adding Song To txt File or Html Table

Problem:
Create a Song Organizer script that stores songs in a text file. Include functionality that allows users to view the song list and prevents the same song name from being entered twice. Also, include code that sorts the songs by name, deletes duplicate entries, and randomizes the song list with the shuffle() function.
How Come my code isnt adding the song to the txt file or the table?
My Solution - > Broken, song isnt being appending to song list
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://w...content-available-to-author-only...3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://w...content-available-to-author-only...3.org/1999/xhtml">
<head>
<title>PHP Code Blocks</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Song Organizer</h1>
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if (isset($_GET['action'])) {
if ((file_exists("SongOrganizer/songs.txt"))
&& (filesize("SongOrganizer/songs.txt")
!= 0)) {
$SongArray = file(
"SongOrganizer/songs.txt");
switch ($_GET['action']) {
case 'Remove Duplicates':
$SongArray = array_unique($SongArray);
$SongArray = array_values($SongArray);
break;
case 'Sort Ascending':
sort($SongArray);
break;
case ’Shuffle’:
shuffle($SongArray);
break;
} // End of the switch statement
if (count($SongArray)>0) {
$NewSongs = implode($SongArray);
$SongStore = fopen("SongOrganizer/songs.txt","wb");
if ($SongStore === false)
echo "There was an error updating the song file\n";
else {
fwrite($SongStore, $NewSongs);
fclose($SongStore);
}
}
else
unlink("SongOrganizer/songs.txt");
}
}
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes(
$_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt")
&& filesize("SongOrganizer/songs.txt")
> 0) {
$ExistingSongs = file(
"SongOrganizer/songs.txt");
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes($_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt")
&& filesize("SongOrganizer/songs.txt")> 0) {
$ExistingSongs = file("SongOrganizer/songs.txt");
}
}
}
}
if ((!file_exists("SongOrganizer/songs.txt"))
|| (filesize("SongOrganizer/songs.txt")
== 0))
echo "<p>There are no songs in the
list.</p>\n";
else {
$SongArray = file(
"SongOrganizer/songs.txt");
echo "<table border=\"1\" width=\"100%\"
style=\"background-color:lightgray\">\n";
foreach ($SongArray as $Song) {
echo "<tr>\n";
echo "<td>" . htmlentities($Song) .
"</td>";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<p>
<a href="SongOrganizer.php?action=Sort%20Ascending">
Sort Song List</a><br />
<a href="SongOrganizer.php?action=Remove%20Duplicates">
Remove Duplicate Songs</a><br />
<a href="SongOrganizer.php?action=Shuffl e">
Randomize Song list</a><br />
</p>
<form action="SongOrganizer.php" method="post">
<p>Add a New Song</p>
<p>Song Name: <input type="text" name="SongName"
/></p>
<p><input type="submit" name="submit"
value="Add Song to List" />
<input type="reset" name="reset"
value="Reset Song Name" /></p>
</form>
</body>
</html>
I just ran your code locally. You're never sending an action in the form so none of the code is executing.
Inside the form, add something like:
<input type="hidden" name="action" value="literally anything can go here" />

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...

Categories