Skip to content

Instantly share code, notes, and snippets.

@johnlettman-old
Created August 6, 2011 18:21
Show Gist options
  • Save johnlettman-old/1129598 to your computer and use it in GitHub Desktop.
Save johnlettman-old/1129598 to your computer and use it in GitHub Desktop.
Natural English list grammar from an array.
<?php
/**
* @author Jonathan Lettman
* @param input Array or String to convert to a natural list.
* @param alphabetical Option to sort the list input alphabetically before turning it into a string.
* @return string Product of Natlist in the natural English grammar of a list.
*/
function natlist($input, $alphabetical = false)
{
if(is_array($input)) $arrayCount = count($input);
else return $input;
if($alphabetical) natsort($input);
switch($arrayCount)
{
case 0: return ''; break;
case 1: return $input[0]; break;
case 2: return implode(' and ', $input); break;
default: # Greater than 2.
$pieces2 = $input[$arrayCount - 1];
unset($input[$arrayCount - 1]);
$pieces1 = implode(', ', $input);
return $pieces1.', and '.$pieces2;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment