Menu
Coddy logo textTech

Displaying a Countdown

Part of the Logic & Flow section of Coddy's PHP journey — lesson 64 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 an event name to display the countdown for.

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"}]

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

The third input will be an event name in this format: Team Meeting

Read all three inputs and decode the JSON string into an events array. Find the event that matches the provided event name. Create DateTime objects for both today's date and the event's date.

Calculate the difference between the event date and today's date. Use the diff() method on the today's DateTime object, passing the event's DateTime object as a parameter. This returns a DateInterval object. Access the days property of this object to get the number of days between the two dates.

Print the countdown in the following format:

Countdown to [event name]: [number of days] days

If the event is not found in the array, print: Event not found

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: An event name to display the countdown for (example: Team Meeting)

Expected output: A single line showing the countdown in the format: Countdown to [event name]: [number of days] days, or Event not found if the event doesn't exist

Try it yourself

<?php
// Read inputs
$jsonString = trim(fgets(STDIN));
$todayDate = trim(fgets(STDIN));
$eventName = trim(fgets(STDIN));

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

// TODO: Write your code below
// Find the event that matches the provided event name
// Create DateTime objects for today's date and the event's date
// Calculate the difference using diff() method
// Access the days property from the DateInterval object

// Output the result
echo $result;
?>

All lessons in Logic & Flow