note 71348 deleted from function.implode by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 13:17:45 +0000 |
| Subject: | note 71348 deleted from function.implode by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189737@lists.php.net to get a copy of this message | ||
Note Submitter: bishop
----
The english_list() implementation of davidpk212 at gmail dot com, Andy Morris, and tshort at cisco
dot com does not handle the case of a two-element array with Oxford comma. Example:
<?php
english_list(array ('a', 'b'), true) // == 'a, and b'
// should be 'a and b'
?>
Here's another implementation that addresses this issue, uses pass-by-reference without
modifying the array, and illustrates yet another approach to solving the problem:
<?php
function english_list(&$array, $useOxfordComma = false) {
$count = (is_array($array) ? count($array) : 0);
if (3 <= $count) {
$last = end($array);
$list = prev($array) . ($useOxfordComma ? ', and ' : ' and ') . $last;
while ($v = prev($array)) {
$list = $v . ', ' . $list;
}
} else if (2 == $count) {
$last = end($array);
$list = prev($array) . ' and ' . $last;
} else if (1 == $count) {
$list = end($array);
} else {
return '';
}
reset($array);
return $list;
}
?>
Run times for this version are comparable to the run times for heir earlier posted versions.