Skip to content

Instantly share code, notes, and snippets.

@danjohnson3141
Created December 13, 2013 15:31
Show Gist options
  • Save danjohnson3141/7945963 to your computer and use it in GitHub Desktop.
Save danjohnson3141/7945963 to your computer and use it in GitHub Desktop.
PHP version of Ruby's to_sentence method. Uses option array as param.
/**
* PHP Equivilent to Ruby's to_sentence method.
* Example:
* to_sentence(array('a', 'b')) = a and b
* to_sentence(array('a', 'b', 'c')) = a, b, and c
* @param array() $items array of items to split
* @param array() $options array of options:
* conjunction = conjunction string (default ' and ')
* seperator = seperator string (default ', ')
* conjunctionSeperator = conjunction seperator (default ',')
*/
function to_sentence($items, $options = null )
{
$defaults = array('conjunction' => ' and ',
'seperator' => ', ',
'conjunctionSeperator' => ',');
if(is_array($options)) {
$options = array_merge($defaults, $options);
} else {
$options = $defaults;
}
if(is_array($items)) {
$lastItem = array_pop($items);
if(count($items) === 0) {
return $lastItem;
}
if(count($items) >= 2 && $options['conjunctionSeperator']) {
$options['conjunction'] = $options['conjunctionSeperator'] . $options['conjunction'];
}
$items = implode($options['seperator'], $items);
$items = $items . $options['conjunction'] . $lastItem;
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment