I am trying to create a quiz whereby user will key in their answer in a textfield. If the answer the user keys in matches with the answer in the array, the score will increase. However my $answer only returns the last value the user entered which does not allow comparison of the user's input with the array, and the score does not increase. Please advice on how to allow the textfield to read the user's input and compare it with the array's answer provided.

<?php
$qtspick_key = array_rand($qtspool, 3);

$pickqts = array(); 
$i = 0;
foreach ($qtspick_key as $key) {
    $pickqts[$i] = $qtspool[$key];
    $i++;
}

    $qtspool = array(
    1 => array(
    'qts' => 'When was The Fast and the Furious released? ', 'ans' => '2001'),
    2 => array(
    'qts' => 'When was The Fast and the Furious: Tokyo Drift released? ', 'ans' => '2006'),
    3 => array(
    'qts' => 'When was Fast & Furious Presents: Hobbs & Shaw released? ', 'ans' => '2019'),
    4 => array(
    'qts' => 'When was Insidious released? ', 'ans' => '2010'),
    5 => array(
    'qts' => 'When was Insidious: Chapter 2 released? ', 'ans' => '2013'),
    6 => array(
    'qts' => 'When was Insidious: Chapter 3 released? ', 'ans' => '2015'),
    7 => array(
    'qts' => 'When was Insidious: The Last Key released? ', 'ans' => '2018'),
    8 => array(
    'qts' => 'When was World War Z released? ', 'ans' => '2013'),
    9 => array(
    'qts' => 'When was The Conjuring released? ', 'ans' => '2013'),
    10 => array(
    'qts' => 'When was The Conjuring 2 released? ', 'ans' => '2016')
    );

?>

<form action="" method="post">

    <?php $score = 0; ?>
    <?php foreach($pickqts as $qtsno => $value) { ?>    
    <?php echo $value['qts'] ?>
    <input type="text" name="user_ans">
    <?php echo $value['ans'] ?><br><br>
    <?php if (isset($_POST["user_ans"])) { ?>
    <?php $answer = $_POST["user_ans"]; ?>
    <?php if ($value['ans'] == $answer) { ?>
    <?php $score++; ?>
    <?php } ?>
    <?php var_dump($value['ans']); ?>
    <?php var_dump($answer); ?>
    <?php } ?>
    <?php } ?>

    <p> Current score: <?php echo $score ?></p>
    <input type="submit" value="Submit Quiz"/>        
</form>

$_POST['user_ans'] will always be just a single value of the textbox.

What does your HTML code look like where there are multiple textboxes where the user types in multiple answers?

There will be 3 questions out of the 10 being populated. So basically there will be 3 questions with 3 textfields for the users to input. I understand that I have to submit an array and i have tried doing name="user_ans[]" at the textfield but it still does not work for me. Im wondering how do I go about it to solve the issue

Oh, I think I see what you're trying to do. Try something like this:

<?php

$question_arr = array(
    0 => array(
        'question' => 'Question Here?',
        'answer' => 'Answer Here.',
    ),
    1 => array(
        'question' => 'Question Here?',
        'answer' => 'Answer Here.',
    ),
    2 => array(
        'question' => 'Question Here?',
        'answer' => 'Answer Here.',
    )        
);

// Pick 3 random questions
$random_questions = array_rand($question_arr, 3);

echo '<form action="" method="post">';

// Foreach of the random questions picked
foreach ($random_questions AS $key => $value)
{

    // Ask the question and present the user with an input box

    echo $value['question'];
    echo "<input type='text' name='$key'>";
}

echo '<input type="submit" value="Submit Quiz">';    
echo '</form>';

// What to do if we are submitting the form

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{

    // Start with a score of 0
    $score = 0;

    // POST names should be the question id
    foreach ($_POST AS $question_id => $user_answer)
    {
        if (isset($question_arr[$question_id]))
        {
            // If the user answer is the same as the answer in the question array
            if ($user_answer = $question_arr[$question_id]['answer'])
            {
                $score++;
            }
        }
    }

    echo 'Score is: ', $score;
}

?>

In other words, it's not working for you because you have 3 textboxes, and each one has the same name "user_ans". That means that you're only sending the last value of user_ans back to the server. In my code, I'm naming each textbox the ID for the question being asked.

i have tried doing name="user_ans[]" at the textfield but it still does not work for me

If you do <input type="text" name="user_ans[]"> for the textfield, what is the value of $_POST?

In other words, what happens when you do something like: var_dump($_POST);?

commented: I agree with this method - makes an array which is easy to process +6
commented: This would be my answer(name="somefield[]") +8

You can't use php interactively on the user side. It is a server protocol. Instead, you need to use javascript or jQuery. Here is a solution the uses JS. Note that I prefer to build the page from php using echo statements rather than exiting php and entering again. This is a personal preference and either approach works.

<!DOCTYPE html>
<html lang='en'>
<head>
</head>
<body>
<?php
    $qtsPool = [
        'When was The Fast and the Furious released?' => '2001',
        'When was The Fast and the Furious: Tokyo Drift released?' => '2006',
        'When was Fast & Furious Presents: Hobbs & Shaw released?' => '2019',
        'When was Insidious released?' => '2010',
        'When was Insidious: Chapter 2 released?' => '2013',
        'When was Insidious: Chapter 3 released?' => '2015',
        'When was Insidious: The Last Key released?' => '2018',
        'When was World War Z released?' => '2013',
        'When was The Conjuring released?' => '2013',
        'When was The Conjuring 2 released?' => '2016'
    ];

    $qtsPickKey = array_rand($qtsPool, 3);

    $pickQts = []; 
    foreach ($qtsPickKey as $key) {
        $pickQts[$key] = $qtsPool[$key];
    }

    echo "<form method='post'>";
    echo "<input type='hidden' name='numPicks' id='numPicksId' value='" . count($pickQts) . "'>";
    $score = 0;
    $idx = 1;
    foreach($pickQts as $qts => $ans) {
        echo "<label for='userAnsId{$idx}' style='font-weight:bold;'>{$qts}:&nbsp;</label>";
        echo "<input type='text' name='userAns$idx' id='userAnsId$idx' onchange='displayRealAns($idx);' tabindex='$idx'>";
        echo "&nbsp;&nbsp;<span id='realAnsId$idx' style='display:none;'>$ans</span><br><br>";
        $idx++;
    }
    echo "<span style='font-weight:bold;'>Current score: </span><span id='scoreId'>{$score}</span></p>";
    echo "<input type='submit' id='submitId' value='Submit Quiz' disabled style='display:none;'>";
    echo "</form>";
?>
<script>
    function displayRealAns(idx) {
        let realAnsId = document.getElementById("realAnsId" + idx),
            userAnsId = document.getElementById("userAnsId" + idx),
            scoreId = document.getElementById("scoreId"),
            numPicks = document.getElementById("numPicksId").getAttribute('value'),
            submitId = document.getElementById("submitId"),
            realAnsVal = realAnsId.innerHTML,
            userAnsVal = userAnsId.value;

        if (realAnsVal == userAnsVal) {
            let score = scoreId.innerHTML;
            score++;
            scoreId.textContent = score;

            realAnsId.style.color = "green";
        } else {
            realAnsId.style.color = "red";
        }

        realAnsId.style.display="inline";
        userAnsId.setAttribute("disabled", "true");

        if (idx == numPicks) {
            submitId.removeAttribute("disabled");
            submitId.style.display="inline";
        }
    }
</script>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.