What is the best way to handle output in PHP so that only unique dates are displayed once, followed by the corresponding names?

When displaying unique dates followed by corresponding names in PHP, one way to handle this is by using an associative array where the date is the key and the names are stored as values in an array. This allows us to easily group names by date and ensure that each date is displayed only once with its corresponding names.

<?php
// Sample data with dates and names
$data = array(
    '2022-01-01' => 'John',
    '2022-01-01' => 'Jane',
    '2022-01-02' => 'Alice',
    '2022-01-03' => 'Bob',
    '2022-01-03' => 'Charlie'
);

// Initialize an empty array to store unique dates and corresponding names
$uniqueDates = array();

// Iterate through the data array to group names by date
foreach ($data as $date => $name) {
    $uniqueDates[$date][] = $name;
}

// Display unique dates followed by corresponding names
foreach ($uniqueDates as $date => $names) {
    echo $date . ': ' . implode(', ', $names) . '<br>';
}
?>