Source Code for /public/05-accepting-input/quiz.php
<?php
$questions = [
[
'question' =>
'Which of these PHP globals might contain user input?',
'options' => [
'$_GET',
'$_POST',
'$_COOKIE',
'All of the above!'
],
'correct_answer' => 'All of the above!',
],
[
'question' =>
'How would I reverse a string in PHP?',
'options' => [
'reverse()',
'strrev()',
'string_reverse()',
"You can't reverse a string in PHP"
],
'correct_answer' => 'strrev()',
],
[
'question' =>
'How would I loop through the items in a PHP array?',
'options' => [
'foreach()',
'each()',
'array_each()',
'for $item of $array'
],
'correct_answer' => 'foreach()',
],
];
function show_question($number, $data){
echo '<p>' . $data['question'] . '</p>';
echo '<ul>';
foreach( $data['options'] as $option ){
echo '<li><label>';
echo '<input type="radio"';
echo ' name="answer[' . $number. ']"';
echo ' value="' . $option . '">';
echo $option;
echo '</label></li>';
}
echo '</ul>';
}
function quiz($questions){
?>
<h1>Quiz time!</h1>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<?php
foreach( $questions as $number => $question ){
show_question( $number, $question );
}
?>
<input type="submit" name="submit" value="See score">
</form>
<?php
}
function results($questions){
$score = 0;
foreach( $questions as $number => $question ){
$correct_answer = $question['correct_answer'];
$their_answer = $_POST['answer'][$number];
if( $their_answer === $correct_answer ){
$score++;
}
}
$max_score = count($questions);
?>
<h1>Quiz results</h1>
<p>
You scored <?php echo $score; ?> out of <?php echo $max_score; ?>!
</p>
<p>
<a href="<?php echo $_SERVER['REQUEST_URI']; ?>">
Have another go?
</a>
</p>
<?php
}
if( $_POST['submit'] ){
results($questions);
} else {
quiz($questions);
}