Search code examples
phparraysstring-comparison

PHP, comparing a value from an Select field (HTML) to a value from an array not working


I'm trying to compare a value that I get from a select (HTML) to a value that is already in an array but for some reason its not working

if(isset($_POST['submit1'])) {
    $selectOption = $_POST['answers'];
    $correctAnswer = $filearray[$question][6];

    $a=(string)$selectOption;
    $b=(string)$correctAnswer;

    echo $a;
    echo $b;

    if ( $a=== $b){
        echo 'Nice answer';
    }else{
        echo 'you failed';
    }
}

When I compare $a with $b I always get 'you failed' even tho they are equal (eg answer is A and correct answer is A as well) I tried to make both a String and to compare them with double equals and also triple equals but I always get the wrong result.

edit:

here is the whole code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Beat the L</title>
</head>
<body>
<h1>Beat the L</h1>

<!--<div id="indexFormDiv">
 <form method="post">
        <label for="Username">Username: </label><input id="Username"     name="Username" type="text" value="" required><br>
    <button name="submit" id="submit" >Let's go</button>
</form>
</div> -->

<?php
$question = 0;
$dataText = file('test.txt');
$arrayAnswers = array(
    2=> 'A',
    3=> 'B',
    4=> 'C',
    5=> 'D'
);

$filearray = array();
$file = fopen("test.txt", "r");
if ($file) {
    $i = 0;

    while (($line = fgets($file)) !== false) {
        $data = explode(":", $line);
        $filearray[$i] = array(
            1 => $data[0],
            2 => $data[1],
            3 => $data[2],
            4 => $data[3],
            5 => $data[4],
            6 => $data[5]
        );
        $i++;
    }

    fclose($file);
} else {
    echo "Couldn't load the questions";
}


echo "Question: " . $filearray[$question][1] . "<br>";

echo "<form method='post' action='". $_SERVER['PHP_SELF']."'>";
echo "Choose your answer: <select name='answers'>";


for ($i = 2; $i <= count($filearray[$question])-1; $i++) {
    echo "<option value='".$arrayAnswers[$i]."'>" .     $filearray[$question][$i] . "</option>";
}

echo "</select><br>";
echo "<input type='submit' name='submit1' id='submit1' ></form>";

if(isset($_POST['submit1'])) {
    $selectOption = $_POST['answers'];
    $correctAnswer = $filearray[$question][6];

    $a=(string)$selectOption;
    $b=(string)$correctAnswer;

    echo $a;
    echo $b;
    if ( $a=== $b){
        echo 'Nice answer';
    } else {
        echo 'you failed';
    }
}
?>
</body>
</html>

Here is my test website: https://students.btsi.lu/oliwi/Jose/login.php


Solution

  • To make it more generic for future use:

    Notice that when reading data from text file and assign to variable there may be a following "" (white-space) or \n therefor it is recommend to use trim before doing any comparison.

    Small hint - if your compare fails use var_dump before the if statement to check the actual values