Skip to content

Instantly share code, notes, and snippets.

@rkulla
Last active September 26, 2015 13:48
Show Gist options
  • Save rkulla/1107063 to your computer and use it in GitHub Desktop.
Save rkulla/1107063 to your computer and use it in GitHub Desktop.
Create english list function
<?php
/**
* Create English List
*
* I wrote this in 2007 for a project I was working on.
*
* Converts arrays like (1,2,3) to a list in English like: "1, 2 and 3"
* If only two array elements exist it returns: "1 and 2"
* If only one array element exists it returns: "1"
* If zero array element exists it returns: ""
* If an array element is an empty string, it is skipped.
*
* @param array $array The array to convert.
* @param bool $oxford Option to put a comma before 'and'. Default False.
* @param bool $add_quotes Option to show quotes around elems. Default False.
* @return string Return an English list or empty string if the array is empty.
*/
function create_english_list($array, $oxford=false, $add_quotes=false) {
$format_str1 = '%s';
if ($oxford) {
$format_str2 = '%s, and %s';
} else {
$format_str2 = '%s and %s';
}
if ($add_quotes) {
$array = array_map(create_function('$val', 'return "\"$val\"";'), $array);
}
// Filter out strings that don't contain at least one letter or number.
$array = array_filter($array, create_function('$val',
'return preg_replace("/[^a-zA-Z0-9]/", "", $val);'));
$nelems = count($array);
if ($nelems == 0) {
return '';
} else {
$last_elem = array_pop($array);
return vsprintf(/* Format string: */
$nelems <= 1 ? $format_str1 : $format_str2,
/* Arguments: */
$nelems <= 1 ? $last_elem : array(implode($array, ', '),
$last_elem)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment