Skip to content

Instantly share code, notes, and snippets.

@gbrock
Created August 24, 2015 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gbrock/910aa946fa2186879c67 to your computer and use it in GitHub Desktop.
Save gbrock/910aa946fa2186879c67 to your computer and use it in GitHub Desktop.
Joins an array of strings into a comma-separated string of readable output.
<?php
/**
* Joins an array of strings into a comma-separated string of readable output.
* Array ['John', 'Paul', 'George', 'Ringo'] becomes the string "John, Paul, George, and Ringo".
*
* @param array $items
* @param bool|true $oxfordComma
* @param string $conjunction
* @return string
*/
function commaSeparatedList($items, $conjunction = 'and', $oxfordComma = true)
{
if (count($items) === 1) {
// The array has only one item, so just return it since it's the entire list.
return array_pop($items);
}
// Set up the Oxford comma with a space, if it's even needed.
$oxfordComma = ($oxfordComma && count($items) > 2 ? ', ' : ' ');
// Remove the last item so we can interject an Oxford comma as necessary
$lastItem = array_pop($items);
return implode($items, ', ') . $oxfordComma . $conjunction . ' ' . $lastItem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment