我正在嘗試一個相當簡單的測試,使用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 –