Reputation: 192
I got a list of 20 questions with A or B answer, and for the result I need to count certain answers together to get a score, and its A and B mixed.
Question 1 <input type="radio" name="1" value="A" />
<input type="radio" name="1" value="B" />
Question 2 <input type="radio" name="2" value="A" />
<input type="radio" name="2" value="B" />
Question 3 <input type="radio" name="3" value="A" />
<input type="radio" name="3" value="B" />
$result1 = $1A + $2B + $4A + $7B etc (count total of these answers)
$result2 = $3B + $5B + $6B etc
the results should be numeric, with checkboxes it would be easy because of unique names so values can be 1, but with radios I don't know how other then a lot of 'if 1=B then $var++', but i'm sure there is an easier way.
Upvotes: 1
Views: 81
Reputation: 1141
Here you go:
<?php
var_dump($_POST);
/*
@param array $userInput - just the $_POST
@param array $expected must be in format : [
[1,'A'],
[2,'B']
]
@return int
*/
function countExpectedAnswers(array $userInput, array $expected) /*: int*/{
$result = 0;
foreach($expected as $ex){
if(isset ($userInput[$ex[0]]) && $userInput[$ex[0]] === $ex[1]){
$result ++;
}
}
return $result;
}
$expectedAnswers = [
[1,'A'],
[2,'A'],
[3,'B']
];
echo 'Answered correctly: ' . countExpectedAnswers($_POST,$expectedAnswers);
?>
<form method = 'post'>
<div>
Question 1 <input type="radio" name="1" value="A" >
<input type="radio" name="1" value="B" >
</div>
<div>
Question 2 <input type="radio" name="2" value="A" >
<input type="radio" name="2" value="B" >
</div>
<div>
Question 3 <input type="radio" name="3" value="A" >
<input type="radio" name="3" value="B" >
</div>
<input type = 'submit' value = 'go'>
</form>
Upvotes: 1