note 71348 added to function.implode
| From: | bishop at osu1 dot php dot net | Date: | Thu, 23 Nov 2006 14:33:04 +0000 |
| Subject: | note 71348 added to function.implode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120025@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 216.194.113.175
Probable Submitter: 24.148.147.65
----
Manual Page -- http://www.php.net/manual/en/function.implode.php
Edit -- https://master.php.net/note/edit/71348
Del: integrated -- https://master.php.net/note/delete/71348/integrated
Del: useless -- https://master.php.net/note/delete/71348/useless
Del: bad code -- https://master.php.net/note/delete/71348/bad+code
Del: spam -- https://master.php.net/note/delete/71348/spam
Del: non-english -- https://master.php.net/note/delete/71348/non-english
Del: in docs -- https://master.php.net/note/delete/71348/in+docs
Del: other reasons-- https://master.php.net/note/delete/71348
Reject -- https://master.php.net/note/reject/71348
Search -- https://master.php.net/manage/user-notes.php