PHP,比较来自 Select 字段 (HTML) 的值与来自数组的值无效

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

我正在尝试将我从 select (HTML) 获得的值与数组中已有的值进行比较,但由于某种原因它不起作用

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';
    }
}

当我将 $a$b 进行比较时,我总是得到 'you failed',即使它们是相等的(例如答案是 A,正确答案也是 A)我尝试同时进行一个字符串并将它们与双等号和三等号进行比较,但我总是得到错误的结果。

编辑:

完整代码如下:

<!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>

这是我的测试网站:https://students.btsi.lu/oliwi/Jose/login.php

为了使其更通用以供将来使用:

注意从文本文件中读取数据并赋值给变量时可能会出现下面的“</code>”(white-space)或<code>\n建议在进行任何比较之前使用 trim

小提示 - 如果您的比较失败,请在 if 语句之前使用 var_dump 来检查实际值