Source Code for /public/05-accepting-input/quiz.php

<?php
// Let's store the questions in an array for easy modification:
$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()',
  ],
];

/**
 * Display a single question and it's options:
 */
function show_question($number, $data){
  echo '<p>' . $data['question'] . '</p>';
  echo '<ul>';
  foreach( $data['options'] as $option ){
    echo '<li><label>';
    // Notice how we assemble the name of this field - like:
    // <input name="answer[1]" value="some answer">
    // PHP recognises the name with square brackets as an
    // array and gives you one at the other end!
    echo '<input type="radio"';
    echo ' name="answer[' . $number. ']"';
    echo ' value="' . $option . '">';
    echo $option;
    echo '</label></li>';
  }
  echo '</ul>';
}

/**
 * Show the form with the questions:
 */
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
}

/**
 * Score the user's answers and give them their results:
 */
function results($questions){
  // Make a variable to keep their score in:
  $score = 0;
  // Loop through each question, and see if they got it right:
  foreach( $questions as $number => $question ){
    // The correct answer comes from the questions array:
    $correct_answer = $question['correct_answer'];
    // Their answer comes from an array that was posted to us:
    $their_answer = $_POST['answer'][$number];
    // If they match, give them a point!
    if( $their_answer === $correct_answer ){
      $score++;
    }
  }
  // What's the best possible score? The number of questions:
  $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 the submit button was pressed (something with
// name="submit"), show the results, otherwise show the quiz:
if( $_POST['submit'] ){
  results($questions);
} else {
  quiz($questions);
}