note 52363 added to function.implode
| From: | AndyMorris at osu1 dot php dot net | Date: | Thu, 28 Apr 2005 17:19:22 +0000 |
| Subject: | note 52363 added to function.implode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-88707@lists.php.net to get a copy of this message | ||
Similar to a previous note, but this works for any length array, plus also works for arrays with key
strings instead of integer keys! I know it's not strictly an implode() example, but it concerns
what you might be considering using implode() to help you to do achieve...
<?php
// Return array as a comma separated list; final two elements separated
// by 'and' with an optional "Oxford" comma preceding the 'and'.
function english_list($array, $oxfordComma=0)
{
$optionalComma = ( $oxfordComma ) ? "," : "";
$str = "";
$size = count( $array );
$i = 0;
foreach ( $array as $item ) {
$str .= $item;
$i++;
if ( $i < $size - 1) $str .= ", ";
elseif ( $i == $size - 1) $str .= $optionalComma." and ";
}
return $str;
}
// test the comma separated list function
echo english_list( array(), 1 )."<br>";
echo english_list( array("foo"), 1 )."<br>";
echo english_list( array("foo", "bar"), 0 )."<br>";
echo english_list( array("a" => "foo", "b" => "bar",
"c" => "foobar"), 1 )."<br>";
echo english_list( array("foo", "bar", "foobar", "barfoo"),
0 )."<br>";
?>
----
Manual Page -- http://www.php.net/manual/en/function.implode.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52363
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52363&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52363&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52363&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52363&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52363&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52363&report=yes
Search -- http://master.php.net/manage/user-notes.php