This article is part of my #100DaysOfCode and #100DaysOfBlogging challenge. R1D21


This Exercism exercise is straight forward.

An extract from the instructions:

Given students’ names along with the grade that they are in, create a roster for the school.

In the end, you should be able to:

  • Add a student’s name to the roster for a grade
  • Get a list of all students enrolled in a grade
  • Get a sorted list of all students in all grades. Grades should sort as 1, 2, 3, etc., and students within a grade should be sorted alphabetically by name.

Note that all our students only have one name. (It’s a small town, what do you want?)

My solution

Although I am not happy with the usage of plain array in PHP, I used them here because of a closed setup where nothing will be added. In a regular project I would implement some custom collection class which checks allows type checking, since Generic Types are not (yet) available in PHP.

<?php

declare(strict_types = 1);

class School
{
    private $students;

    public function add(string $name, int $grade) : void
    {
        $this->initGradeIfItDoesNotExist($grade);

        $this->students[$grade][] = $name;
        sort($this->students[$grade]);
    }

    public function grade(int $grade) : array
    {
        $this->initGradeIfItDoesNotExist($grade);
        return $this->students[$grade];
    }

    public function studentsByGradeAlphabetical() : array
    {
        asort($this->students);
        return $this->students;
    }

    private function initGradeIfItDoesNotExist(int $grade) : void
    {
        if (! isset($this->students[$grade])) {
            $this->students[$grade] = [];
        }
    }
}