2011-04-17 86 views
1

我很難比較用戶輸入的$ _POST和一組數組值。如何將POST響應與數組值進行比較?

我已經設置下列變量...

$response = $_POST['answer']; 

...和選定的一範圍的可能正確答案,並將它們存儲在一個陣列...

$solutions = array('answer1','answer2','answer3'); 

I」已經試過檢查/這樣比較......

if (value($response) !== ($solutions) 
{$error['result'] = "Wrong answer.";} 

我知道這是行if (value($response) !== ($solutions)

回答

4

in_array()是你的朋友:

$correct = in_array($response, $solutions); 
0
$answer = false; 

foreach ($solutions as $sol) 
{ 
    if ($sol == $_POST['answer']) 
    { 
     $answer = $sol; 
     break; 
    } 
} 

if ($answer) 
{ 
    //GOOD 
} 
else 
{ 
    $error['result'] = "Wrong answer." 
} 
1

如果要比較數組值; as harakiri寫道in_array()是你的朋友。

但是,如果你想比較數組鍵,你必須使用; array_key_exists()

我想提醒你壽,如果你的數組包含了大量的信息與in_array檢查它()會讓你放慢腳步。

相反,你將不得不用isset()來檢查它是否被設置,它比in_array()快得多。