【问题标题】:How to use if & else to find an answer in an array?如何使用 if & else 在数组中查找答案?
【发布时间】:2014-11-15 05:58:13
【问题描述】:

我在简单的 PHP 应用程序中遇到问题,用户必须从可用选项列表中输入正确答案。这些选项存储在一个数组中。问题是除了数组声明点之外,我不能在脚本中的任何时候使用这些选项。我可能听起来很愚蠢......我是,相信我。假设这是数组:

$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");

现在我的脚本中有一个文本框,$_POST 方法用于提交表单。我选择的正确选择是“运动”。现在有 4 种用户可能点击提交的可能性,它们在下面列出。

  1. 用户单击提交按钮时未在文本框中输入任何文本。
  2. 用户猜错了选项,来自$hobbyChoices,但不是“Sports”。
  3. 用户猜测不是来自数组的选项。即除数组中的内容之外的任何内容。
  4. 最后,用户输入了正确的选项“Sports”。

这似乎很简单,但问题是我不能在脚本中的任何地方使用爱好的名称,如前所述,除了数组声明。我能得到帮助吗?此外,当我尝试执行 4 种可能性中的一种时,我遇到了大写和小写的问题。这真的很烦人,任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 1) 请展示您的尝试。粘贴代码,而不是仅仅描述它。 2) 使用选择框。这样,选择不在列表中的选项的可能性很小(尽管您仍然需要检查它),以及在错误情况下回答的可能性。

标签: php html arrays if-statement conditional-statements


【解决方案1】:

如果我正确理解您的问题,那么您正在寻找以下内容:

<?php 
    $hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");

    if (isset($_POST['answer'])) {
        $answer = mysql_real_escape_string($_POST['answer']);
        $correct_answer = $hobbyChoices[4];
        $response = "Your answer is not one of the answers listed!";

        foreach ($hobbyChoices as $value) {
            if (strtolower($answer) == strtolower($value) && (strtolower($answer) != strtolower($correct_answer))) {
                $response = "You selected the wrong answer from the list of options!";
            }
            else if (strtolower($answer) == strtolower($value) && (strtolower($answer) == strtolower($correct_answer))) {
                $response = "You have answered correctly!";
            }
        }

        print $response;
    }
?>

<form name="form" method="post">
    <table>
        <tr>
            <td>What is baseball?
            </td>
            <td><input type="text" name="answer" />
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="submit" />
            </td>
        </tr>
    </table>
</form>

strtolower 是 php 中的一个函数,可以将字符串转换为小写,并帮助您比较两个值。

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2016-02-16
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2015-11-03
    • 1970-01-01
    • 2015-02-14
    相关资源
    最近更新 更多