Alan
Alan

Reputation: 111

How to compare POST response to array values?

I'm having difficulty comparing the $_POST from a user input to a set of array values.

I've set the following variable ...

$response = $_POST['answer'];

... and selected a range of possible correct answers and stored them in an array ...

$solutions = array('answer1','answer2','answer3');

I've tried checking/comparing like this ...

if (value($response) !==  ($solutions)
{$error['result'] = "Wrong answer.";}

I know it's the line if (value($response) !== ($solutions).

Upvotes: 1

Views: 1328

Answers (3)

Revenant
Revenant

Reputation: 2984

If you want to compare array values; as harakiri wrote in_array() is your friend.

However if you want to compare array keys, you have to use; array_key_exists()

I would like to warn you tho, if your array contains a lot of information checking it with in_array() will slow you down.

Instead you will have to go with isset() to check if it is set, it is much faster than in_array().

Upvotes: 1

PiZzL3
PiZzL3

Reputation: 2220

$answer = false; 

foreach ($solutions as $sol)
{
    if ($sol == $_POST['answer'])
    {
        $answer = $sol;
        break; 
    }
}

if ($answer)
{
    //GOOD
}
else
{
    $error['result'] = "Wrong answer."
}

Upvotes: 0

cweinberger
cweinberger

Reputation: 3588

in_array() is your friend:

$correct = in_array($response, $solutions);

Upvotes: 4

Related Questions