CodeBlanks Logo Icon CodeBlanks

Computing the score

PHP course · Intermediate · Lesson 45/115

Walk all questions with foreach and compute the correct count.

Quiz class and score method

To hold multiple questions in one package, you'll define a Quiz class. Its public array $questions property stores question objects in an array. The constructor takes this array and assigns it to the property.

To compute the score you add a score(array $answers): int method. This method walks all questions with a foreach loop, calls isCorrect on each, and counts the correct ones. The $answers parameter is an array of the user's answer indexes, one per question.

Counter with the accumulator pattern

Inside the score method you keep a $correct counter. It starts at $correct = 0;. As you walk each question with foreach, if the answer is correct you increment with $correct++. Finally you return the total with return $correct;.

This is the accumulator pattern: a variable is initialized, conditionally incremented inside a loop, and returned at the end. It's a common pattern for scores, averages, totals and similar calculations.

Exercise Add the Quiz class and score method

After the Question class, define a Quiz class. Add a public array $questions; property and a public function __construct(array $questions = []) constructor; inside it assign $this->questions = $questions;. Then add a public function score(array $answers): int method. Inside it initialize $correct = 0;, walk with foreach ($this->questions as $i => $q), check with if ($q->isCorrect($answers[$i] ?? -1)), and increment with $correct++ when correct. Finally return with return $correct;. Load two questions with $quiz = new Quiz([...]); and print the score with echo $quiz->score([0, 1]);.

Show example solution
int { $correct = 0; foreach ($this->questions as $i => $q) { if ($q->isCorrect($answers[$i] ?? -1)) { $correct++; } } return $correct; } }. Load two questions with $quiz = new Quiz([ new Question("What is PHP?", ["Scripting language", "Database", "Browser"], 0), new Question("Which is a loop?", ["if", "for", "echo"], 1), ]); and print with echo $quiz->score([0, 1]);.
Example solution:
<?php
// Question + Quiz classes for score calculation
class Question {
    public string $text = "";
    public array $options = [];
    public int $answerIndex = 0;

    public function __construct(string $text, array $options, int $answerIndex) {
        $this->text = $text;
        $this->options = $options;
        $this->answerIndex = $answerIndex;
    }

    public function isCorrect(int $choice): bool {
        return $choice === $this->answerIndex;
    }
}

class Quiz {
    public array $questions;

    public function __construct(array $questions = []) {
        $this->questions = $questions;
    }

    public function score(array $answers): int {
        $correct = 0;
        foreach ($this->questions as $i => $q) {
            if ($q->isCorrect($answers[$i] ?? -1)) {
                $correct++;
            }
        }
        return $correct;
    }
}

$quiz = new Quiz([
    new Question("What is PHP?", ["Scripting language", "Database", "Browser"], 0),
    new Question("Which is a loop?", ["if", "for", "echo"], 1),
]);
echo $quiz->score([0, 1]);

Test yourself

  1. What does a foreach loop do?

    • Only increments numbers by one
    • Defines a class
    • Reads a file
    • Walks through all elements of an array in order
    Show answer

    Walks through all elements of an array in order — Correct. foreach walks all elements of an array in order and runs the loop body for each.

  2. Complete the element part of the foreach loop

    foreach ($this->questions as ____) {
        if ($q->isCorrect($answers[$i] ?? -1)) {
            $correct++;
        }
    }
    Show answer
    foreach ($this->questions as $i => $q) {
        if ($q->isCorrect($answers[$i] ?? -1)) {
            $correct++;
        }
    }
  3. Match the score calculation concepts

    foreach
    Loop construct
    $correct
    Counter variable
    $correct++
    Increment counter
    return $correct
    Returns the total

All lessons in Intermediate