The table of contents

Exercise 8 of 9 in chapter 2 · 150 XP · 4 objectives checked by tests

Topics covered: Arrow functionfnarray_filter()count()instanceof

Madame Lou finds the front page a bit long to skim before her mail round. She wants one line at the very top that sums up the issue: “In this issue: 4 articles and 1 classified ad.” And no way is she counting again by hand for every issue: PHP knows how to filter and count an array.

Your mission

The Sommaire class (table of contents) is already declared: it receives the publications, and for now its versHtml() method returns an empty string.

  1. In versHtml(), keep only the articles with array_filter() and an arrow function that tests instanceof Article. Do the same for the ads, with instanceof Annonce.
  2. Return <p class="sommaire">In this issue: 4 articles and 1 classified ad.</p>, counting with count(). Only 1 is singular: “1 article”, “1 classified ad”, but “0 classified ads” and “2 classified ads”.
  3. In <main class="articles">, display the table of contents before the publications: (new Sommaire($publications))->versHtml().

Reminder

An arrow function is an anonymous function made of a single expression, written with fn: fn (int $n): int => $n * 2 returns double what it receives, with no return and no braces.

You pass it to array_filter($tableau, fn ($x) => …), which calls it on each element and keeps the ones for which it returns true. count($tableau) counts the elements.

For singular or plural, the ternary operator (exercise 4) does the trick: $nombre === 1 ? ' article' : ' articles'.