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

1 Answer

0 votes
// Return all last Fridays of each month in a given year
function lastFridaysOfYear(int $year): iterable {
    for ($month = 1; $month <= 12; $month++) {

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

        // Walk backward to Friday
        while ($date->format('N') != 5) {   // 5 = Friday
            $date->modify('-1 day');
        }

        yield $date;
    }
}

$year = $argv[1] ?? 2026;

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


/*
run:

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

*/

 



answered May 23 by avibootz

Related questions

...