How to find the dates of the last Sunday of each month of a given year in PHP

2 Answers

0 votes
class LastSundays
{
    // Return all last Sundays of each month in a given year
    public static function lastSundaysOfYear(int $year): array
    {
        $results = [];

        for ($month = 1; $month <= 12; $month++) {

            // Last day of the month
            $date = new DateTime("$year-$month-01");
            $date->modify('first day of next month');
            $date->modify('-1 day');

            // Walk backward to Sunday
            while ((int)$date->format('w') !== 0) { // Sunday = 0
                $date->modify('-1 day');
            }

            $results[] = clone $date;
        }

        return $results;
    }
}

$year = ($argc > 1)
    ? intval($argv[1])
    : 2026;

foreach (LastSundays::lastSundaysOfYear($year) as $date) {
    echo $date->format('m/d/Y') . PHP_EOL;
}


/*
run:

01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026

*/

 



answered 11 hours ago by avibootz
0 votes
// Return all last Sundays of each month in a given year
function lastSundaysOfYear(int $year): array
{
    $results = [];

    for ($month = 1; $month <= 12; $month++) {

        // Last day of the month
        $date = new DateTime("$year-$month-01");
        $date->modify('first day of next month');
        $date->modify('-1 day');

        // Walk backward to Sunday
        while ((int)$date->format('w') !== 0) { // Sunday = 0
            $date->modify('-1 day');
        }

        $results[] = clone $date;
    }

    return $results;
}

$year = ($argc > 1)
    ? intval($argv[1])
    : 2026;

foreach (lastSundaysOfYear($year) as $date) {
    echo $date->format('m/d/Y') . PHP_EOL;
}



/*
run:

01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026

*/

 



answered 10 hours ago by avibootz

Related questions

...