Skip to content

Instantly share code, notes, and snippets.

@danjohnson3141
Last active December 30, 2015 06:59
Show Gist options
  • Save danjohnson3141/7793395 to your computer and use it in GitHub Desktop.
Save danjohnson3141/7793395 to your computer and use it in GitHub Desktop.
Like Ruby's to_sentance, this function returns a list separated by commas. Last item will be proceeded by "and". Example: prettyList(('a', 'b')) returns "a and b", prettyList(('a', 'b', 'c')) returns "a, b, and c". Alternate version with option array instead of individual params.
<?php
function prettyList($list)
{
$listCount = sizeOf($list);
if($listCount == 1) {
$listString = $list[0];
}
if($listCount == 2) {
$listString = implode(' and ', $list);
}
if($listCount > 2) {
$lastItem = array_pop($list);
$listString = implode(', ', $list);
$listString .= ', and ' . $lastItem;
}
return $listString;
}
// Even better - from Titan (Miles Johnson)
public static function listing($items, $glue = ' and ', $sep = ', ')
{
if (is_array($items)) {
$lastItem = array_pop($items);
if (count($items) === 0) {
return $lastItem;
}
$items = implode($sep, $items);
$items = $items . $glue . $lastItem;
}
return $items;
}
// Test:
// -----
$speakers1 = array('Dan');
$speakers2 = array('Dan', 'Michael');
$speakers3 = array('Dan', 'Michael', 'Nathan');
echo 'Speakers1:<br>' . prettyList($speakers1) . '<br><br>';
echo 'Speakers2:<br>' . prettyList($speakers2) . '<br><br>';
echo 'Speakers3:<br>' . prettyList($speakers3) . '<br><br>';
// Output:
// -------
//Speakers1:
//Dan
//Speakers2:
//Dan and Michael
//Speakers3:
//Dan, Michael, and Nathan
?>
/**
* 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