Coding cleanly and correctly, or unlike me
Posted on July 30th, 2008 in PHP, Programming, Web Development
Today a friend of mine asked me if I knew of a way to find the next 12 months (starting with next month) and returning an array of those months and their corresponding year. I told him that I was certain that I could do something like this and set out to do it. I came up with:
<?php /** * Gets the next 12 months of the year, starting again at January. * * This function will return an array of 'month year' for the next twelve months * * @access public * @return array Array of month and year strings */ function getNextMonths() { /** * Get this month by number * * Using the numeric value of the month allows for easy transposition into a * new array. */ $tm = date('n'); /** * Get this year - because we will need this for the string output */ $ty = date('Y'); /** * Array of months keyed at 1 * * These are keyed at 1 because the date() function does this */ $ms = array(1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); /** * Create a variable to hold out output array */ $ma = array(); /** * Now build the array, using only one loop */ for ($j = 1, $i = $tm; $j <= 12; $i++, $j++, $ma[$j] = $i <= 12 ? "$ms[$i] $ty" : $ms[$i-12].' '.($ty+1)); /** * Send back what we just made */ return $ma; } /** * Output control - for the record, I do not count this as a line of code :-) */ header('Content-Type: text/plain'); /** * Test it */ var_dump(getNextMonths()); ?>
Thinking that I had found the promise land with the awesome little bit of my brainy goodness I posed this problem to my coworker as a code challenge (we do that from time to time to keep our brains thinking). To my surprise and glee, my coworker came through and kick my sorry ass all over the place with his little piece of goodness (I added the comments):
<?php /** * Gets the next 12 months from this month * * @return array Array of "month year" strings */ function getNextMonths() { for ($i = 1; $i < 13; $i++) { $array[] = date('F Y', mktime(0, 0, 0, date('m') + $i, 1, date('y'))); } return $array; } // Test it var_dump(getNextMonths()); ?>
Arrogance is of the devil and I think I have taken my fair share of it. Congrats Jason, you put me in my place. And Mark is now a little happier too because you totally gave him some kick ass code.
Now to open the discussion a tad… which one do you like and why? Comment away. I would be interested to see your comments.
No Responses to “Coding cleanly and correctly, or unlike me”
There are currently no comments on this post. But you can change that...