-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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