我正在尝试一个相当简单的测试,使用HTML复选框,用户可以选择最多四个项目(我的测试中的食物)。所选项目被传递给一个PHP脚本,在那里我根据选定的项目检查它们以确定用户选择的内容。比较字符串时无法使IF语句正常工作
基于此,我使用if语句来确定用户选择的内容,并将二进制值写入数组以供将来处理(这是下一个要解决的项目)。
我的问题是,我不能让if
声明成为现实。正如你从代码中看到的,我使用trim
来去掉多余的字符,并使用var_dump
和print
命令查看我在输入一组语句之前所拥有的内容。
到目前为止似乎都不错,但if
声明从来都不是真实的(我在每个声明中都放回声明以告诉我)。下面是有关代码的一部分,以及PHP脚本的输出,当我选择所有四种食品时。我很欣赏任何见解。
ps - 我也试过strcmp
来代替IF语句,无济于事。
的PHP:
for ($i=0; $i<count($userChecked); $i++) {
// var_dump to show what exactly was passed
trim($userChecked[$i]);
var_dump($userChecked[$i]);
print "<pre>[".$userChecked[$i]."]</pre>";
// now go through each checked item to see where the match is
// echo that we have a match and set the corresponding array value to 1
if ($userChecked[i]=="soup") {
echo "the user wants soup<br />";
$pref_array[0] = '1';
}
if ($userChecked[i]=="salad") {
echo "the user wants salad<br />";
$pref_array[1] = '1';
}
if ($userChecked[i]=="cheese") {
echo "the user wants cheese<br />";
$pref_array[2] = '1';
}
if ($userChecked[i]=="sardines") {
echo "the user wants sardines<br />";
$pref_array[3] = '1';
}
}
当选择所有的复选框的输出(汤,色拉,奶酪,沙丁鱼):
串(4) “汤” [汤] 串( 5) “色拉” [沙拉] 串(6) “干酪” [乳酪] 串(8) “沙丁鱼” [沙丁鱼]
你想要$ userChecked [$ i]不是[i] - 我不是一个在范围中定义的常量。打开错误报告,你会更快地找出这些类型的错误:) – Martin
@Martin夏普的眼睛。 :) –
也许最好比较字符串与http://php.net/manual/en/function.strcmp.php –