How can PHP handle sorting DateTime objects in an array?

When working with arrays of DateTime objects in PHP, sorting them can be a bit tricky due to the nature of DateTime objects. To sort DateTime objects in an array, you can use the usort() function along with a custom comparison function that compares the timestamps of the DateTime objects.

// Array of DateTime objects
$dates = [
    new DateTime('2022-01-15'),
    new DateTime('2022-01-10'),
    new DateTime('2022-01-20')
];

// Custom comparison function to sort DateTime objects
usort($dates, function($a, $b) {
    return $a <=> $b;
});

// Output sorted DateTime objects
foreach ($dates as $date) {
    echo $date->format('Y-m-d') . "\n";
}