How can an array output generated by a for loop be sorted by date in PHP?

When generating an array output using a for loop in PHP, the dates may not be in chronological order. To sort the array by date, you can use the usort function along with a custom comparison function that compares the dates. This will rearrange the array elements in ascending or descending order based on the dates.

// Sample array output generated by a for loop
$dates = array("2022-03-15", "2022-03-10", "2022-03-20", "2022-03-05");

// Custom comparison function for sorting dates
function compareDates($a, $b) {
    return strtotime($a) - strtotime($b);
}

// Sort the array by date
usort($dates, "compareDates");

// Output the sorted array
print_r($dates);