What are some potential pitfalls when sorting posts by date in PHP?

One potential pitfall when sorting posts by date in PHP is not properly formatting the date string before sorting. This can lead to incorrect sorting results, as the dates may not be in a format that can be compared correctly. To solve this, you can use the strtotime() function to convert the date string into a Unix timestamp before sorting.

// Sample array of posts with dates
$posts = array(
    array('title' => 'Post 1', 'date' => '2022-01-15'),
    array('title' => 'Post 2', 'date' => '2022-01-10'),
    array('title' => 'Post 3', 'date' => '2022-01-20')
);

// Sort the posts by date
usort($posts, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

// Output sorted posts
foreach ($posts as $post) {
    echo $post['title'] . ' - ' . $post['date'] . PHP_EOL;
}