Skip to content

Instantly share code, notes, and snippets.

@CatEntangler
Last active February 26, 2018 15:41
Show Gist options
  • Save CatEntangler/ded615e69f1a46536ebe3077ec62c711 to your computer and use it in GitHub Desktop.
Save CatEntangler/ded615e69f1a46536ebe3077ec62c711 to your computer and use it in GitHub Desktop.
function GetSentenceList( ARRAY $things, STRING $operator = "and", BOOL $oxfordComma = TRUE ) {
if( empty( $things ) ) {
return FALSE;
}
$oxford = ( $oxfordComma )
? ', '
: ' ';
switch( count( $things ) ) {
case 1:
case 2:
return implode( " {$operator} ", $things );
default:
// Need to convert to numerical values because math.
$things = array_values( $things );
$secondToLast = $things[ count( $things ) - 2 ];
$lastThing = end( $things );
reset( $things );
$string = '';
foreach( $things as $thing ) {
if( $thing === $secondToLast ) {
$string .= "{$thing}{$oxford}{$operator} ";
}
elseif( $thing === $lastThing ) {
$string .= "{$thing}";
}
else {
$string .= "{$thing}, ";
}
}
return $string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment