Skip to content
PHP Logo

How can one efficiently compare multiple dates in PHP to only display those within the next 4 weeks?

To efficiently compare multiple dates in PHP to only display those within the next 4 weeks, you can use the DateTime class to manipulate dates and calculate differences between them. By comparing each date with the current date and checking if it falls within the next 4 weeks, you can filter out the dates that meet this criteria.

php
$currentDate = new DateTime();
$fourWeeksLater = new DateTime('+4 weeks');

$dates = [/* array of dates to compare */];

foreach ($dates as $date) {
    $dateObj = new DateTime($date);
    if ($dateObj >= $currentDate && $dateObj <= $fourWeeksLater) {
        echo $dateObj->format('Y-m-d') . "\n";
    }
}