The Oxford Comma

Here's a little function I wrote today because I needed to be able to turn a list of between one and three items into a string like 'apples, oranges, and pears', 'apples and pears', or just 'stairs'.

I figured I might as well handle everything in one place, and throw in the option to have an 'or' instead of an 'and'. There may be occasions you don't want the Oxford comma, but I can't think of any.

* Grammatically fun helper to make a list of things in a sentence, ie
* turn an array into a string 'a, b, and c'.
* @param $list
*  An array of words or items to join.
* @param $type
*  The text to use between the last two items. Defaults to 'and'.
* @param $oxford
*  Change this from default and you are a philistine.
function oxford_comma_list($list, $type = 'and', $oxford = TRUE) {
  $final_join = " $type ";
  if ($oxford && count($list) > 2) {
    $final_join = ',' . $final_join;
  $final = array_splice($list, -2, 2); 
  $final_string = implode($final_join, $final);
  array_push($list, $final_string);
  return implode(', ', $list);

Now the real question: how would you make this translatable?


by stephthegeek on Wed, 30/06/2010 - 18:09

I just wanted to point out a neat little module that does this with CCK text fields:

by greg.harvey on Fri, 02/07/2010 - 14:33

LOL, "there's a module for that..." - of course. Love it. In your face, Joachim! ;-)

by joachim.noreiko on Fri, 02/07/2010 - 19:07

Double ha -- my use case was outside of CCK; it was for messages returned from a form depending on how many checkboxes were selected.

But yes that looks cool.

by langworthy on Wed, 30/06/2010 - 21:32

This function is simply beautiful.

by mikeytown2 on Wed, 30/06/2010 - 22:08

I think we need a library of text formatters, put it in a module that everyone can then require.

One of my first projects with modifying a module

The semi abandoned module based off of this work

by Budda on Wed, 30/06/2010 - 22:19

My fav type of comma seperated list.

by Anonymous on Fri, 02/07/2010 - 15:27

I think you meant 'separated'.

by Chris Cohen on Thu, 01/07/2010 - 09:14

I like the way you describe this as "grammatically fun" - is there such a thing, or is that an oxymoron? ;)

This is a nice little function and one that deserves to get used, I think, just like Drupal's format_plural().

The translation issue is an interesting one, because I have no idea how these sorts of lists are represented in other languages, or whether grammar has the same meaning, or even importance.

Post new comment

© 2010 Greg Harvey. Drupal theme by Kiwi Themes.