What is the best practice for retrieving the earliest value from a DateTime array in PHP?
When retrieving the earliest value from a DateTime array in PHP, the best practice is to use the `min()` function along with a custom comparison function. This allows you to compare the DateTime objects in the array and find the earliest one.
// Sample DateTime array
$dateTimes = [
new DateTime('2022-01-01'),
new DateTime('2022-03-15'),
new DateTime('2022-02-10')
];
// Custom comparison function to compare DateTime objects
function compareDates($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Retrieve the earliest DateTime value from the array
$earliestDate = min($dateTimes, 'compareDates');
echo $earliestDate->format('Y-m-d'); // Output: 2022-01-01