Skip to content

Instantly share code, notes, and snippets.

@BrainFeeder
Forked from gbrock/CommaSeparatedList.php
Created January 4, 2017 11:57
Show Gist options
  • Save BrainFeeder/d272015e6e8ca58a4c27c373af41a26f to your computer and use it in GitHub Desktop.
Save BrainFeeder/d272015e6e8ca58a4c27c373af41a26f 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