PHP One-Liners – Array of Month Names and Numbers

PHP DevelopmentOne of the most elegant features of PHP is its flexibility in array manipulation.  Since the language implements weak type-checking, interesting functionality can be built in less lines of code than that required by more traditional web languages.

In this tutorial, we’ll go over a PHP one-liner that creates an associative array of month numbers to month names.  In this specific implementation, it is useful for plug-in to a drop-down list-of-values generator, however the techniques used are broadly applicable to a variety of situations.

The code is as follows:

array_reduce(range(1,12),function($rslt,$m){ $rslt[$m] = date('F',mktime(0,0,0,$m,10)); return $rslt; })

And produces the following array:

Array (
[1] => January
[2] => February
[3] => March
[4] => April
[5] => May
[6] => June
[7] => July
[8] => August
[9] => September
[10] => October
[11] => November
[12] => December )

There are three primary functions that make this technique work – range, date, and array_reduce.

Range is a convenient PHP function for numerical analysis, which works similar to the Matlab pre-populated array definitions.  Given a start value, end value, and step size, the range function will populate an array in shorthand without requiring the developer to write out each individual item.

Next, the date function takes the work out of translating a numerical value (1 through 12), to the actual month name.  By plugging the numerical month into the mktime function, a date object is created.  Then that date object with the proper month is parsed by the date function to return the human-readable month name.

The heavy lifting, however, is done by the array_reduce function.  Although normally this function is used to calculate sums or aggregates over an array of values, it can also walk over an array and iteratively perform a folding operation.  Array_reduce syntax is as follows:

mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
mixed callback ( mixed $carry , mixed $item )

The way the function works, is that array_reduce iteratively calls the “callback” function for each element in the array.  As it does so, it also passes along a running value, or result, that is modified by each iteration of the call.  This running result is called the “carry”.

In this application, array_reduce takes an array of the 12 numerical months, and then creates a new array of month number to month name pairs.  As each month is processed, that value is added to the result array, until it is finally passed back upon completion as the return value of the array_reduce function.

Although this operation could be programmed using several lines of code and an iterator, the one-liner highlights the list-folding capabilities of PHP, and provides an easy way to dynamically generate associative arrays for in-line HTML processing.

Written by Andrew Palczewski

About the Author
Andrew Palczewski is CEO of apHarmony, a Chicago software development company. He holds a Master's degree in Computer Engineering from the University of Illinois at Urbana-Champaign and has over ten years' experience in managing development of software projects.
Google+

RSS Twitter LinkedIn Facebook Email

8 thoughts on “PHP One-Liners – Array of Month Names and Numbers”

  1. Thank you for this great tip. I just have a website with calendar application and it is so helpful to print this kind of output.
    Do you know about the simple PHP commands and functions listing to be utilized in the web applications?

  2. I see you share interesting content here, you can earn some extra money, your blog has big
    potential, for the monetizing method, just type in google
    - K2 advices how to monetize a website

  3. This one is a two-liner, but it supports alternative calendars:

    $calendarInfo = cal_info(CAL_GREGORIAN);
    $months = array_combine(range(1, count($calendarInfo['months'])), $calendarInfo['months']);

    You could also replace ‘months’ with ‘abbrevmonths’ to get 1=>’Jan’, 2=>’Feb’ and so on.

  4. Wow, that is a great line, added Start from this month, in case you want to return the months starting from this month
    $months = array_reduce(range(1, 12), function($rslt, $m, $startFromThisMonth = true) {$rslt[abs($m)] = date(‘F’, mktime(0, 0, 0, abs($m)));return ((count($rslt) > 11) && $startFromThisMonth) ? $rslt = array_slice($rslt, date(‘n’) – 1, 12, true) + array_slice($rslt, 0, date(‘n’) – 1, true) : $rslt;});

Leave a Reply to Michael Cancel reply

Your email address will not be published. Required fields are marked *