PHP,将来自Select字段(HTML)的值与数组中的值进行比较不起作用

3
我试图比较从一个选择器(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时,即使它们相等(例如答案是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

请提供包含 $_POST['answers'] 的选择字段,以及 $filearray 变量和 $question 变量。缺少这些信息,无法提供帮助。 - Laurens
完成了,感谢您的回答。 - Wilson Silva
@LightZumo 不是<options>的value属性是$arrayAnswers$filearray[$question][6]只是选项的文本,而不是值。 - Laurens
一个单词- trim 注意 D 后面的空格... - dWinder
@dWinder 你说得对,天啊!我解决了这个问题,问题出在我的文本文件里! - Wilson Silva
显示剩余5条评论
1个回答

0
为了更好地适用于未来:请注意,从文本文件读取数据并分配给变量时可能会有以下 ""(空格)或 \n,因此建议在进行任何比较之前使用 trim
小提示-如果您的比较失败,请在 if 语句之前使用 var_dump 检查实际值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接