i have a form that i've made a custom security question for.
It randomizes a question with the code
$rand1 = rand ( 1,20 );
$rand2 = rand ( 1,20 );
$randsvar = $rand1 + $rand2;
$securefråga = "Vad blir " . $rand1 . "+" . $rand2;
and i then parse it in to my code as
$_POST["secure"]
after that i convert them both to integers and compare both the converted $randsvar and the form value with eachother with the code
$intSecure = intval($secure);
$intRand = intval($randsvar);
if($intSecure == $intRand)
{
$errorNummer++;
}
else
{
$secureErr = "wrong answer";
}
however even if i type the correct answer it gives me the error message, what am i doing wrong?
You can use sessions to save the current operation. If submitted, compare the user input to the saved session total. Rough example:
if(!isset($_POST['submit'])) {
$_SESSION['rand1'] = rand(1, 20);
$_SESSION['rand2'] = rand(1, 20);
$_SESSION['randsvar'] = $_SESSION['rand1'] + $_SESSION['rand2'];
} else {
$input = $_POST['input'];
if($input == $_SESSION['randsvar']) {
echo 'correct';
} else {
echo 'incorrect';
}
exit;
}
?>
<form method="POST">
<label>
<?php echo $_SESSION['rand1'] . ' + ' . $_SESSION['rand2'] . ' = '; ?>
<input type="text" name="input" />
<input type="submit" name="submit" />
</label>
</form>
Related
i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission
so i have a script which i need to redirect the user to a certain .php based on their entry. They will enter a user id like "user_123" the suffix will be extracted using strpos eg "123". So "123" should redirect to "123.php" etc
Here's the code i have for strpos part:
index.php
<html>
<form action="check.php" method="post">
User_number:<br>
<input type="email" name="usernum" value="" required><br><br>
<input type="submit" value="Submit">
</form>
</html>
check.php
<?
$data = ['usernum'];
$request = substr($data, strpos($data, "_") + 1);
//added echo just for visual purposes
echo $request;
?>
How do i use the $request value to check against lets say an array, to redirect me to 123.php?
Create an if/else statement that will return an error message if no "_" is present in the form entry?
Thanks
$page_name=$_POST['usernum'];
$pos=strpos($page_name,"-");
if($pos==true){
$request = substr($page_name, strpos($page_name, "_") + 1);
//added echo just for visual purposes
header(Location:$request.".php");
}
else{ echo "your user number must be in this form user - user number ";
}
?>
Try:
<?php
if (isset($_POST['usernum'])) {
$data = $_POST['usernum'];
} else {
$data = "";
}
$pos = strpos($data, "_");
if (!$pos) {
echo "No _ found!";
} else {
$request = substr($data, ++$pos);
$valid_ids = array("123", "456", "789");
if (!is_numeric($request) || !in_array($request, $valid_ids)) {
echo "Invalid user ID!";
} else {
header("Location: http://www.yourdomain.com/" + $request + ".php");
}
}
?>
My code should provide two random numbers and have the user enter their product (multiplication).
If you enter a wrong answer, it tells you to guess again, but keeps the same random numbers until you answer correctly. Answer correctly, and it starts over with a new pair of numbers.
The below code changes the value of the two random numbers even if I entered the wrong number. I would like to keep the values the same until the correct answer is entered.
<?php
$num1=rand(1, 9);
$num2=rand(1, 9);
$num3=$num1*$num2;
$num_to_guess = $num3;
echo $num1."x".$num2."= <br>";
if ($_POST['guess'] == $num_to_guess)
{ // matches!
$message = "Well done!";
}
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
else
{ // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="answer" value="<?php echo $answer;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<?php echo $expression; ?> <input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
In order to keep the same numbers, you have to store them on the page and then check them when the form is submitted using php. You must also set the random number if the form was never submitted. In your case, you were always changing num1 and num2. I tried to leave as much of your original code intact, but it still needs some work to simplify it.
First I added 2 more hidden field in the html called num1 and num2
Second, I set $num1 and $num2 to the value that was submitted from the form.
After following the rest of the logic, I make sure that $num1 and $num2 are reset if the answer is correct of it the form was never submitted.
You can see the comments in the code below.
Additionally, if you were going to use this in a production environment, you would want to validate the values being passed in from the form so that malicious users don't take advantage of your code. :)
<?php
// Setting $num1 and $num2 to what was posted previously and performing the math on it.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num_to_guess = $num1*$num2;
// Check for the correct answer
if ($_POST && $_POST['guess'] == $num_to_guess)
{
// matches!
$message = "Well done!";
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
// If the form wasn't submitted i.e. no POST or something else went wrong
else
{
// Only display this message if the form was submitted, but there were no expected values
if ($_POST)
{
// some other condition and only if something was posted
$message = "I am terribly confused.";
}
// set num1 and num2 if there wasn't anything posted
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Show the problem
echo $num1."x".$num2."= <br>";
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="num1" value="<?= $num1 ?>" />
<input type="hidden" name="num2" value="<?= $num2 ?>" />
<input type="hidden" name="answer" value="<?php echo $num3;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
When you load the page for the first time, you have (i.e.) “2*3” as question. $_POST is not defined, so if ($_POST['guess']... will produce a undefined index warning. Then you echo $message, but where you define $message? $_POST['guess'] is undefined, so is evaluated as 0, $num_to_guess is 6 (=2*3), so $message is set to " is too small! Try a larger number.", even if the user has not input anything. The hidden answer is set to $answer, but this variable is not defined so it is set to nothing (or to “Notice: Undefined variable: answer”, if you activate error reporting). Same issue for expression input and for echo $expression.
Try something like this:
$newQuestion = True; // This variable to check if a new multiplication is required
$message = '';
/* $_POST['guess'] check only if form is submitted: */
if( isset( $_POST['guess'] ) )
{
/* Comparison with answer, not with new result: */
if( $_POST['guess'] == $_POST['answer'] )
{
$message = "Well done!";
}
else
{
/* If result if wrong, no new question needed, so we propose same question: */
$newQuestion = False;
$answer = $_POST['answer'];
$expression = $_POST['expression'];
if( $_POST['guess'] > $_POST['answer'] )
{
$message = "{$_POST['guess']} is too big! Try a smaller number.";
}
else
{
$message = "{$_POST['guess']} is too small! Try a larger number.";
}
}
}
/* New question is generated only on first page load or if previous answer is ok: */
if( $newQuestion )
{
$num1 = rand( 1, 9 );
$num2 = rand( 1, 9 );
$answer = $num1*$num2;
$expression = "$num1 x $num2";
if( $message ) $message .= "<br>Try a new one:";
else $message = "Try:";
}
?>
<!DOCTYPE html>
(... Your HTML Here ...)
This might also be fun to learn. This is a session. Lets you store something temporarily. It is a little dirty. But fun to learn from.
http://www.w3schools.com/php/php_sessions.asp
<?php
session_start(); // Starts the Session.
function Save() { // Function to save $num1 and $num2 in a Session.
$_SESSION['num1'] = rand(1, 9);
$_SESSION['num2'] = rand(1, 9);
$_SESSION['num_to_guess'] = $_SESSION['num1']*$_SESSION['num2'];;
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// If there is no session set
if (!isset($_SESSION['num_to_guess'])) {
Save();
$message = "";
}
if (isset($_POST['guess'])) {
// Check for the correct answer
if ($_POST['guess'] == $_SESSION['num_to_guess']) {
$message = "Well done!";
session_destroy(); // Destroys the Session.
Save(); // Set new Sessions.
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too big! Try a smaller number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too small! Try a larger number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// some other condition
else {
$message = "I am terribly confused.";
}
}
?>
<html>
<body>
<h2><?php echo $Som . '<br>'; ?>
<?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
I tried to make a dice script in php that should look like this one:
http://u11626.hageveld2.nl/po/opdracht1b/index.php
this is the link to mine:
http://u10511.hageveld2.nl/po/opdracht1b/index.php
Sorry if the answer is really obvious but i just can't figure out why the script doesn't work.
btw: "knop" means "button",and the pictures that I use as dices are called dobbelsteen1, dobbelsteen2 ..... dobbelsteen 6
<?php
session_start();
if (!isset($_SESSION["d1"]) || !isset($_SESSION["d2"]) || !isset($_SESSION["d3"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop1"])) {
$_SESSION["d1"]=0;
}
elseif (isset($POST["knop2"])) {
$_SESSION["d2"]=0;
}
elseif (isset($POST["knop3"])) {
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop4"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
echo "d1 =" . $_SESSION["d1"];
echo "d2 =" . $_SESSION["d2"];
echo "d3 =" . $_SESSION["d3"];
if ($_SESSION["d1"]==0) {
$f = rand(1,6);
}
if ($_SESSION["d2"]==0) {
$g=rand(1,6);
}
if ($_SESSION["d3"]==0) {
$h=rand(1,6);
}
echo $f;
for ($r=1; $r<4; $r++) {
if (!$f==0) {
$f = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $f . ".gif'>
<form method='post'>
<input type='submit' name='knop1' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$g==0) {
$g = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $g . ".gif'>
<form method='post'>
<input type='submit' name='knop2' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$h==0) {
$h = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $h . ".gif'>
<form method='post'>
<input type='submit' name='knop3' value='Dobbelsteen gooien'>
</form>
";
}
}
?>
i have written what i consider an optimal script for this dice throwing exercise you are doing. I am giving you all the answers here but hopefully you will research my approach and learn from it.
<?php
//Start the php session
session_start();
//Initialise local dice array
//Check the session variable for already set values, if not set a random value
//Use TERNARY OPERATORS here to avoid multipl if else
$dice = array(
0 => (!empty($_SESSION['dice'][0])) ? $_SESSION['dice'][0] : rand(1, 6),
1 => (!empty($_SESSION['dice'][1])) ? $_SESSION['dice'][1] : rand(1, 6),
2 => (!empty($_SESSION['dice'][2])) ? $_SESSION['dice'][2] : rand(1, 6)
);
//If form has been submitted, and our expected post var is present, check the dice we want to role exists, then role it
//$_POST['roll_dice'] holds the index of the local dice value array element we need to update
if(!empty($_POST['roll_dice']) && !empty($dice[intval($_POST['roll_dice'])])){
$dice[intval($_POST['roll_dice'])] = rand(1, 6);
}
//Save the updated values to the session
$_SESSION['dice'] = $dice;
//Loop over the dice and output them
foreach($dice as $dice_index => $dice_val){
echo "<div class='dice' style='height:100px;width:100px;background-color:red;text-align:center;margin-bottom:50px;padding-top:10px;'>";
echo "<p style='style='margin-bottom:20px;'>".$dice_val."</p>";
echo "<form method='post'>";
echo "<input type='hidden' name='roll_dice' value='".$dice_index."' />";
echo "<input type='submit' value='Roll Dice' />";
echo "</form>";
echo "</div>";
}
?>
To add a new dice simply increase the size of the $dice array. For example the next one would be:
3 => (!empty($_SESSION['dice'][3])) ? $_SESSION['dice'][3] : rand(1, 6)
and then 4, and so on.
I hope this helps.
There are couple of issues with your script, as #Marc B has said "you never save the random numbers back into the session" also you are accessing the post data using $POST where as it should be $_POST, hope that can help you fixing your script.
I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>