What are the best practices for sorting dates in PHP when the date format needs to be maintained as tt.mm.yyyy?

When sorting dates in PHP with the format tt.mm.yyyy, it's important to convert the dates to a format that PHP can understand for proper sorting. One way to achieve this is by using the DateTime class to convert the dates to a sortable format, such as yyyy-mm-dd. Once the dates are converted, they can be easily sorted using PHP's array sorting functions.

$dates = ['31.12.2022', '15.03.2022', '25.07.2022'];

// Convert dates to a sortable format
$sortableDates = [];
foreach ($dates as $date) {
    $dateObj = DateTime::createFromFormat('d.m.Y', $date);
    $sortableDates[$date] = $dateObj->format('Y-m-d');
}

// Sort the dates
asort($sortableDates);

// Output sorted dates in original format
foreach ($sortableDates as $originalDate => $sortableDate) {
    echo $originalDate . "\n";
}