# Php > Databases Code Examples

## Count how many weeks in the month have a specified day

``` Count how many weeks in the month have a specified day <? // // count how many weeks in the month have a specified day, such as Monday. // we know there will be 4 or 5, so no need to check for \$weeks<4 or \$weeks>5 // // Initial formula doesn't work well, so I "reversed-engineered" to get the formula. // 0 - Sunday,...,6 - Saturday for (\$year = 2001; \$year <= 2037; \$year++) { for (\$month = 1; \$month <= 12; \$month++) { \$num_of_days = date("t", mktime(0,0,0,\$month,1,\$year)); echo "<HR> Month=\$month Year=\$year <BR>"; echo "Number of days = \$num_of_days <BR>"; \$firstdayname = date("D", mktime(0, 0, 0, \$month, 1, \$year)); \$firstday = date("w", mktime(0, 0, 0, \$month, 1, \$year)); \$lastday = date("t", mktime(0, 0, 0, \$month, 1, \$year)); echo "First day of the month = \$firstday,\$firstdayname <BR> "; for (\$day_of_week = 0; \$day_of_week <= 6; \$day_of_week++) { if (\$firstday > \$day_of_week) { // means we need to jump to the second week to find the first \$day_of_week \$d = (7 - (\$firstday - \$day_of_week)) + 1; } elseif (\$firstday < \$day_of_week) { // correct week, now move forward to specified day \$d = (\$day_of_week - \$firstday + 1); } else { // my "reversed-engineered" formula if (\$lastday==28) // max of 4 occurences each in the month of February with 28 days \$d = (\$firstday + 4); elseif (\$firstday==4) \$d = (\$firstday - 2); elseif (\$firstday==5 ) \$d = (\$firstday - 3); elseif (\$firstday==6) \$d = (\$firstday - 4); else \$d = (\$firstday - 1); if (\$lastday==29) // only 1 set of 5 occurences each in the month of February with 29 days \$d -= 1; } \$d += 28; // jump to the 5th week and see if the day exists if (\$d > \$lastday) { \$weeks = 4; } else { \$weeks = 5; } if (\$day_of_week==0) echo "Sun "; elseif (\$day_of_week==1) echo "Mon "; elseif (\$day_of_week==2) echo "Tue "; elseif (\$day_of_week==3) echo "Wed "; elseif (\$day_of_week==4) echo "Thu "; elseif (\$day_of_week==5) echo "Fri "; else echo "Sat "; echo "occurences = \$weeks <BR> "; } // for \$day_of_week loop } // for \$mth loop } // for \$year loop ?> ```