Skip to main content
Joachim's blog

Main navigation

  • Home
  • About

Breadcrumb

  1. Home

The Oxford Comma

By joachim, Wed, 30/06/2010 - 15:59

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?

Tags

  • drupal
  • php
  • theming
  • drupal planet
  • text

Frequent tags

  • Drupal Code Builder (9)
  • git (7)
  • module builder (6)
  • 6.x (5)
  • drupal commerce (4)
  • development (3)
  • Entity API (3)
  • Field API (3)
  • patching (3)
  • Composer (3)
  • Drush (3)
  • contributing code (2)
  • contrib module (2)
  • maintaining projects (2)
  • code style (2)
  • drupal.org (2)
  • debugging (2)
  • tests (2)
  • multisite (2)
  • core (2)
  • issue queue (2)
  • Drupal core (2)
  • roadmap (2)
  • 7.x (2)
  • modules (2)
  • developer tools (2)
  • Rector (2)
  • wtf (2)
Powered by Drupal