Menu
Coddy logo textTech

Filtering Events by Month

Part of the Logic & Flow section of Coddy's PHP journey — lesson 63 of 68.

challenge icon

Challenge

Easy

You will receive three inputs: a JSON string representing an array of events, a date string in YYYY-MM-DD format representing today's date, and a month number (1-12) to filter by.

The first input will be a JSON string in this format: [{"name":"Team Meeting","date":"2024-04-15","location":"Office"},{"name":"Conference","date":"2024-05-20","location":"Convention Center"},{"name":"Workshop","date":"2024-04-25","location":"Library"}]

The second input will be a date string in this format: 2024-04-01

The third input will be a month number in this format: 4

Read all three inputs and decode the JSON string into an events array. Filter the events to include only those that meet both conditions:

  • The event date is greater than or equal to today's date (upcoming events only)
  • The event occurs in the specified month

Use DateTime objects to compare dates and extract the month from each event's date using the format() method with the "n" format character (which returns the month as a number without leading zeros).

After filtering, print each matching event in the following format:

Event in month [month]: [name] on [date] at [location]

Print each event on a separate line, in the order they appear in the array. If no events match both criteria, do not print anything.

Input format:

  • First line: A JSON string representing the events array with keys name, date, and location
  • Second line: A date string in YYYY-MM-DD format representing today's date (example: 2024-04-01)
  • Third line: A month number from 1 to 12 (example: 4 for April)

Expected output: Each event that is both upcoming and in the specified month, printed on a separate line in the format: Event in month [month]: [name] on [date] at [location]

Try it yourself

<?php
// Read inputs
$jsonInput = trim(fgets(STDIN));
$todayDate = trim(fgets(STDIN));
$monthNumber = intval(trim(fgets(STDIN)));

// Decode JSON into array
$events = (array)json_decode($jsonInput, true);

// TODO: Write your code below
// Filter events that are upcoming and in the specified month
// Use DateTime objects to compare dates
// Print each matching event in the required format

?>

All lessons in Logic & Flow