Created
August 6, 2011 18:21
-
-
Save johnlettman-old/1129598 to your computer and use it in GitHub Desktop.
Natural English list grammar from an array.
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 | |
/** | |
* @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