PHP: Calculating the Number of Days in a Month Programming 18 APR 2009

green php elephants - elephpantsWow, stumbled across this extremely clever, one line of PHP code to return the correct number of days for any given month, courtesy of the extremely talented David Walsh.

Now while PHP does have an inbuilt function to handle this query (cal_days_in_month), it isn’t always the most ideal of saviors when you consider that it is only valid for PHP 4.0.7 and above installations. David’s on the other hand simply makes use of good old logic and thus pretty much roles out to just about any version of PHP.

And the function? Well, it’s a simple enough call that requires only the target month and year as inputs and looks like this:

function get_days_in_month($month, $year){
   return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}

Very clever Mr. Walsh.

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.