How can the DateTime extension in PHP be utilized to efficiently count the number of specific weekdays within a given time interval?

To efficiently count the number of specific weekdays within a given time interval using the DateTime extension in PHP, you can iterate through each day within the interval and check if it matches the desired weekday. You can then increment a counter for each match found.

// Define the start and end dates of the time interval
$start_date = new DateTime('2022-01-01');
$end_date = new DateTime('2022-01-31');

// Define the desired weekday to count (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
$desired_weekday = 1; // Count Mondays

// Initialize a counter for the number of desired weekdays found
$count = 0;

// Iterate through each day within the interval and count the desired weekdays
while ($start_date <= $end_date) {
    if ($start_date->format('N') == $desired_weekday) {
        $count++;
    }
    $start_date->modify('+1 day');
}

// Output the total count of desired weekdays within the interval
echo "Total count of desired weekdays: " . $count;