Php 如何使用if&;还要在数组中找到答案吗?
我在使用简单的PHP应用程序时遇到了一个问题,用户必须从可用选项列表中输入正确答案。选项存储在一个数组中。问题是除了数组声明点之外,我不能在脚本中的任何时候使用这些选项。我可能听起来很蠢…相信我,我是。假设这是数组:Php 如何使用if&;还要在数组中找到答案吗?,php,html,arrays,if-statement,conditional-statements,Php,Html,Arrays,If Statement,Conditional Statements,我在使用简单的PHP应用程序时遇到了一个问题,用户必须从可用选项列表中输入正确答案。选项存储在一个数组中。问题是除了数组声明点之外,我不能在脚本中的任何时候使用这些选项。我可能听起来很蠢…相信我,我是。假设这是数组: $hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping"); 现在,我的脚本中有一个文本框,$\u POST方法用于提交表单。我选择的正确选择是“运动”。现在,用户可以单击提交4种可能性,如
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
现在,我的脚本中有一个文本框,$\u POST
方法用于提交表单。我选择的正确选择是“运动”。现在,用户可以单击提交4种可能性,如下所示
$hobbyChoices
中猜到了错误的选择,而不是“运动”谢谢 如果我正确理解了你的问题,以下是你要找的:
<?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中的一个函数,它将字符串转换为小写,并帮助您比较两个值 1)请展示您的尝试。除了描述代码之外,还要粘贴代码。2) 使用选择框。这样,选择不在列表中的选项的可能性很小(尽管您仍然需要检查它),在错误情况下回答的可能性也很小。