Menu
Coddy logo textTech

Sorting Events by Date

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

challenge icon

Challenge

Easy

You will receive two inputs: a JSON string representing an array of events, and a date string in YYYY-MM-DD format representing today's date.

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-03-10","location":"Library"}]

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

Read both inputs and decode the JSON string into an events array. Filter the events to include only upcoming events (events whose date is greater than or equal to today's date).

Sort the upcoming events by their date in ascending order (earliest date first) using usort() with a custom comparison function. The comparison function should compare the dates of two events and return a value that determines their order.

After sorting, print each upcoming event in the following format:

Upcoming: [name] on [date] at [location]

Print each event on a separate line, in chronological order from earliest to latest date.

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)

Expected output: Each upcoming event printed on a separate line in chronological order in the format: Upcoming: [name] on [date] at [location]

Try it yourself

<?php
// Read the JSON string of events
$eventsJson = fgets(STDIN);
$events = (array)json_decode($eventsJson, true);

// Read today's date
$todayDate = trim(fgets(STDIN));

// TODO: Write your code below
// Filter upcoming events (date >= today's date)
// Sort the upcoming events by date using usort()
// Print each upcoming event in the required format

?>

All lessons in Logic & Flow