PHP program to find number of days in every week between two given date ranges

To find the number of days in every week between two given date ranges in PHP, we can use the DateTime class to iterate through dates and count occurrences of each weekday.

Example

The following example counts how many times each day of the week occurs between two dates ?

<?php
   $start = "11-11-2019";
   $end = "12-12-2019";
   
   $week_day = array('Monday' => 0,
   'Tuesday' => 0,
   'Wednesday' => 0,
   'Thursday' => 0,
   'Friday' => 0,
   'Saturday' => 0,
   'Sunday' => 0);
   
   $start = new DateTime($start);
   $end = new DateTime($end);
   
   while($start <= $end)
   {
      $time_stamp = strtotime($start->format('d-m-Y'));
      $week = date('l', $time_stamp);
      $week_day[$week] = $week_day[$week] + 1;
      $start->modify('+1 day');
   }
   
   echo "The number of days between the given range is:<br>";
   print_r($week_day);
?>
The number of days between the given range is:
Array
(
   [Monday] => 5
   [Tuesday] => 5
   [Wednesday] => 5
   [Thursday] => 5
   [Friday] => 4
   [Saturday] => 4
   [Sunday] => 4
)

How It Works

The program creates two DateTime objects from the given date strings and initializes an array with all weekdays set to zero. It then iterates through each date in the range, determines the day of the week using date('l'), and increments the corresponding counter in the array. The modify('+1 day') method advances to the next date until the end date is reached.

Conclusion

This method efficiently counts weekday occurrences between two dates using PHP's DateTime class. The loop continues until all dates in the range are processed, providing a complete breakdown of days per week.

Updated on: 2026-03-15T09:03:28+05:30

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements