Skip to content
PHP Logo

What is the best way to sort results in an array by date in PHP?

When sorting results in an array by date in PHP, you can use the `usort` function along with a custom comparison function that compares the dates. This allows you to sort the array based on the date values.

php
// Sample array of results with date values
$results = [
    ['date' => '2022-01-15'],
    ['date' => '2022-02-10'],
    ['date' => '2022-01-05'],
];

// Custom comparison function to compare dates
function compareDates($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}

// Sort the results array by date
usort($results, 'compareDates');

// Output the sorted results
print_r($results);