The below code shows the process of validating 2 input fields. At the end i return in Json the Boolean result of each input.
Imagine i will do the following 20 more times, the code is large. How can an i perform the same procedure with shorter code?
$res =false;
$res2 = false;
if(isset($_POST['Ans1'])) //if user checked ans1 radio
{
if($_POST['Ans1'] == "x divides y") #correct answer
{
$res = true;
}
else{#wrong answer
$res = false;
}
}
else{ #not checked
$res = false;
}
if(isset($_POST['Ans2'])) //if user checked ans2 radio
{
if($_POST['Ans2'] == "x greater than y") #correct answer
{
$res2 = true;
}
else{#wrong answer
$res2 = false;
}
}
else{ #not checked
$res2 = false;
}
echo json_encode(['an1'=>$res,'an2'=>$res2]);
You can use a function to check answer like this one:
function checkAnswer($key, $val) {
$mapping = [
'Ans1' => 'x divides y',
'Ans2' => 'x greater than y'
];
return $mapping[$key] == $val;
}
You will need a mapping of answers. You can then loop the POST array to check the answers; if POST only has answers.
$result = [];
foreach($_POST as $key => $val) {
$res = checkAnswer($key, $val);
$result[$key] = $res;
}
echo json_encode($result);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments