PHP: Find number of weeks in a given month

The following function finds the number of weeks in a given month, assuming Monday as the first day of the week.

  1. <?php
  2. function weeks_in_month($month, $year) {
  3. // Start of month
  4. $start = mktime(0, 0, 0, $month, 1, $year);
  5. // End of month
  6. $end = mktime(0, 0, 0, $month, date('t', $start), $year);
  7. // Start week
  8. $start_week = date('W', $start);
  9. // End week
  10. $end_week = date('W', $end);
  11.  
  12. if ($end_week < $start_week) { // Month wraps
  13. return ((52 + $end_week) - $start_week) + 1;
  14. }
  15.  
  16. return ($end_week - $start_week) + 1;
  17. }